text stringlengths 8 4.13M |
|---|
mod window;
pub use self::window::Window;
mod colors;
pub use self::colors::Colors;
mod attributes;
pub use self::attributes::Attributes;
mod capabilities;
pub use self::capabilities::Capabilities;
mod input;
pub use self::input::Input;
mod add;
pub use self::add::Add;
|
#![feature(test)]
extern crate base64;
extern crate rand;
extern crate test;
use base64::display;
use base64::{decode, decode_config_buf, decode_config_slice, encode, encode_config_buf,
encode_config_slice, Config, MIME, STANDARD};
use rand::Rng;
use test::Bencher;
#[bench]
fn encode_3b(b: &mut Bencher) {
do_encode_bench(b, 3)
}
#[bench]
fn encode_3b_reuse_buf(b: &mut Bencher) {
do_encode_bench_reuse_buf(b, 3, STANDARD)
}
#[bench]
fn encode_3b_slice(b: &mut Bencher) {
do_encode_bench_slice(b, 3, STANDARD)
}
#[bench]
fn encode_50b(b: &mut Bencher) {
do_encode_bench(b, 50)
}
#[bench]
fn encode_50b_display(b: &mut Bencher) {
do_encode_bench_display(b, 50)
}
#[bench]
fn encode_50b_reuse_buf(b: &mut Bencher) {
do_encode_bench_reuse_buf(b, 50, STANDARD)
}
#[bench]
fn encode_50b_slice(b: &mut Bencher) {
do_encode_bench_slice(b, 50, STANDARD)
}
#[bench]
fn encode_100b(b: &mut Bencher) {
do_encode_bench(b, 100)
}
#[bench]
fn encode_100b_reuse_buf(b: &mut Bencher) {
do_encode_bench_reuse_buf(b, 100, STANDARD)
}
#[bench]
fn encode_500b(b: &mut Bencher) {
do_encode_bench(b, 500)
}
#[bench]
fn encode_500b_reuse_buf(b: &mut Bencher) {
do_encode_bench_reuse_buf(b, 500, STANDARD)
}
#[bench]
fn encode_500b_reuse_buf_mime(b: &mut Bencher) {
do_encode_bench_reuse_buf(b, 500, MIME)
}
#[bench]
fn encode_3kib(b: &mut Bencher) {
do_encode_bench(b, 3 * 1024)
}
#[bench]
fn encode_3kib_display(b: &mut Bencher) {
do_encode_bench_display(b, 3 * 1024)
}
#[bench]
fn encode_3kib_reuse_buf(b: &mut Bencher) {
do_encode_bench_reuse_buf(b, 3 * 1024, STANDARD)
}
#[bench]
fn encode_3kib_slice(b: &mut Bencher) {
do_encode_bench_slice(b, 3 * 1024, STANDARD)
}
#[bench]
fn encode_3kib_reuse_buf_mime(b: &mut Bencher) {
do_encode_bench_reuse_buf(b, 3 * 1024, MIME)
}
#[bench]
fn encode_3mib(b: &mut Bencher) {
do_encode_bench(b, 3 * 1024 * 1024)
}
#[bench]
fn encode_3mib_display(b: &mut Bencher) {
do_encode_bench_display(b, 3 * 1024 * 1024)
}
#[bench]
fn encode_3mib_reuse_buf(b: &mut Bencher) {
do_encode_bench_reuse_buf(b, 3 * 1024 * 1024, STANDARD)
}
#[bench]
fn encode_3mib_slice(b: &mut Bencher) {
do_encode_bench_slice(b, 3 * 1024 * 1024, STANDARD)
}
#[bench]
fn encode_10mib(b: &mut Bencher) {
do_encode_bench(b, 10 * 1024 * 1024)
}
#[bench]
fn encode_10mib_reuse_buf(b: &mut Bencher) {
do_encode_bench_reuse_buf(b, 10 * 1024 * 1024, STANDARD)
}
#[bench]
fn encode_30mib(b: &mut Bencher) {
do_encode_bench(b, 30 * 1024 * 1024)
}
#[bench]
fn encode_30mib_reuse_buf(b: &mut Bencher) {
do_encode_bench_reuse_buf(b, 30 * 1024 * 1024, STANDARD)
}
#[bench]
fn encode_30mib_slice(b: &mut Bencher) {
do_encode_bench_slice(b, 30 * 1024 * 1024, STANDARD)
}
#[bench]
fn decode_3b(b: &mut Bencher) {
do_decode_bench(b, 3)
}
#[bench]
fn decode_3b_reuse_buf(b: &mut Bencher) {
do_decode_bench_reuse_buf(b, 3)
}
#[bench]
fn decode_3b_slice(b: &mut Bencher) {
do_decode_bench_slice(b, 3)
}
#[bench]
fn decode_50b(b: &mut Bencher) {
do_decode_bench(b, 50)
}
#[bench]
fn decode_50b_reuse_buf(b: &mut Bencher) {
do_decode_bench_reuse_buf(b, 50)
}
#[bench]
fn decode_50b_slice(b: &mut Bencher) {
do_decode_bench_slice(b, 50)
}
#[bench]
fn decode_100b(b: &mut Bencher) {
do_decode_bench(b, 100)
}
#[bench]
fn decode_100b_reuse_buf(b: &mut Bencher) {
do_decode_bench_reuse_buf(b, 100)
}
#[bench]
fn decode_500b(b: &mut Bencher) {
do_decode_bench(b, 500)
}
#[bench]
fn decode_500b_reuse_buf(b: &mut Bencher) {
do_decode_bench_reuse_buf(b, 500)
}
#[bench]
fn decode_3kib(b: &mut Bencher) {
do_decode_bench(b, 3 * 1024)
}
#[bench]
fn decode_3kib_reuse_buf(b: &mut Bencher) {
do_decode_bench_reuse_buf(b, 3 * 1024)
}
#[bench]
fn decode_3kib_slice(b: &mut Bencher) {
do_decode_bench_slice(b, 3 * 1024)
}
#[bench]
fn decode_3mib(b: &mut Bencher) {
do_decode_bench(b, 3 * 1024 * 1024)
}
#[bench]
fn decode_3mib_reuse_buf(b: &mut Bencher) {
do_decode_bench_reuse_buf(b, 3 * 1024 * 1024)
}
#[bench]
fn decode_3mib_slice(b: &mut Bencher) {
do_decode_bench_slice(b, 3 * 1024 * 1024)
}
#[bench]
fn decode_10mib(b: &mut Bencher) {
do_decode_bench(b, 10 * 1024 * 1024)
}
#[bench]
fn decode_10mib_reuse_buf(b: &mut Bencher) {
do_decode_bench_reuse_buf(b, 10 * 1024 * 1024)
}
#[bench]
fn decode_30mib(b: &mut Bencher) {
do_decode_bench(b, 30 * 1024 * 1024)
}
#[bench]
fn decode_30mib_reuse_buf(b: &mut Bencher) {
do_decode_bench_reuse_buf(b, 30 * 1024 * 1024)
}
#[bench]
fn decode_30mib_slice(b: &mut Bencher) {
do_decode_bench_slice(b, 30 * 1024 * 1024)
}
fn do_decode_bench(b: &mut Bencher, size: usize) {
let mut v: Vec<u8> = Vec::with_capacity(size * 3 / 4);
fill(&mut v);
let encoded = encode(&v);
b.bytes = encoded.len() as u64;
b.iter(|| {
let orig = decode(&encoded);
test::black_box(&orig);
});
}
fn do_decode_bench_reuse_buf(b: &mut Bencher, size: usize) {
let mut v: Vec<u8> = Vec::with_capacity(size * 3 / 4);
fill(&mut v);
let encoded = encode(&v);
let mut buf = Vec::new();
b.bytes = encoded.len() as u64;
b.iter(|| {
decode_config_buf(&encoded, STANDARD, &mut buf).unwrap();
test::black_box(&buf);
buf.clear();
});
}
fn do_decode_bench_slice(b: &mut Bencher, size: usize) {
let mut v: Vec<u8> = Vec::with_capacity(size * 3 / 4);
fill(&mut v);
let encoded = encode(&v);
let mut buf = Vec::new();
buf.resize(size, 0);
b.bytes = encoded.len() as u64;
b.iter(|| {
decode_config_slice(&encoded, STANDARD, &mut buf).unwrap();
test::black_box(&buf);
});
}
fn do_encode_bench(b: &mut Bencher, size: usize) {
let mut v: Vec<u8> = Vec::with_capacity(size);
fill(&mut v);
b.bytes = v.len() as u64;
b.iter(|| {
let e = encode(&v);
test::black_box(&e);
});
}
fn do_encode_bench_display(b: &mut Bencher, size: usize) {
let mut v: Vec<u8> = Vec::with_capacity(size);
fill(&mut v);
b.bytes = v.len() as u64;
b.iter(|| {
let e = format!("{}", display::Base64Display::standard(&v));
test::black_box(&e);
});
}
fn do_encode_bench_reuse_buf(b: &mut Bencher, size: usize, config: Config) {
let mut v: Vec<u8> = Vec::with_capacity(size);
fill(&mut v);
let mut buf = String::new();
b.bytes = v.len() as u64;
b.iter(|| {
encode_config_buf(&v, config, &mut buf);
buf.clear();
});
}
fn do_encode_bench_slice(b: &mut Bencher, size: usize, config: Config) {
let mut v: Vec<u8> = Vec::with_capacity(size);
fill(&mut v);
let mut buf = Vec::new();
b.bytes = v.len() as u64;
// conservative estimate of encoded size
buf.resize(size * 2, 0);
b.iter(|| {
encode_config_slice(&v, config, &mut buf);
});
}
fn fill(v: &mut Vec<u8>) {
let cap = v.capacity();
// weak randomness is plenty; we just want to not be completely friendly to the branch predictor
let mut r = rand::weak_rng();
while v.len() < cap {
v.push(r.gen::<u8>());
}
}
|
use crate::internal::commas;
use crate::Assign;
use std::fmt;
/// The definition of an input to a block.
///
/// These are essentially phi nodes, and makes sure that there's a local
/// variable declaration available.
#[derive(Debug, Clone)]
pub struct Phi {
/// The blocks which defines the variable.
dependencies: Vec<Assign>,
}
impl Phi {
/// Construct a new phi node.
pub(crate) fn new() -> Self {
Self {
dependencies: Vec::new(),
}
}
/// Extend with the given iterator.
pub(crate) fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = Assign>,
{
self.dependencies.extend(iter);
}
}
impl fmt::Display for Phi {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.dependencies.is_empty() {
write!(f, "φ(?)")?;
} else {
write!(f, "φ({})", commas(&self.dependencies))?;
}
Ok(())
}
}
|
use super::utils::GTK_EVENT_HANDLER;
use super::utils::GTK_MUTEX;
use std::cell::RefCell;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
use super::utils::gtk_init_check;
use super::AsGtkDialog;
struct FutureState<R, D> {
waker: Option<Waker>,
data: Option<R>,
dialog: Option<D>,
}
unsafe impl<R, D> Send for FutureState<R, D> {}
pub(super) struct GtkDialogFuture<R, D> {
state: Arc<Mutex<FutureState<R, D>>>,
}
unsafe impl<R, D> Send for GtkDialogFuture<R, D> {}
impl<R: Default + 'static, D: AsGtkDialog + 'static> GtkDialogFuture<R, D> {
pub fn new<B, F>(build: B, cb: F) -> Self
where
B: FnOnce() -> D + Send + 'static,
F: Fn(&mut D, i32) -> R + Send + 'static,
{
let state = Arc::new(Mutex::new(FutureState {
waker: None,
data: None,
dialog: None,
}));
{
let state = state.clone();
std::thread::spawn(move || {
let request = Rc::new(RefCell::new(None));
let callback = {
let state = state.clone();
let request = request.clone();
// Callbacks are called by GTK_EVENT_HANDLER so the GTK_MUTEX is allready locked, no need to worry about that here
move |res_id| {
let mut state = state.lock().unwrap();
if let Some(mut dialog) = state.dialog.take() {
state.data = Some(cb(&mut dialog, res_id));
}
// Drop the request
request.borrow_mut().take();
if let Some(waker) = state.waker.take() {
waker.wake();
}
}
};
GTK_MUTEX.run_locked(|| {
let mut state = state.lock().unwrap();
if gtk_init_check() {
state.dialog = Some(build());
}
if let Some(dialog) = &state.dialog {
unsafe {
dialog.show();
let ptr = dialog.gtk_dialog_ptr();
connect_response(ptr as *mut _, callback);
}
} else {
state.data = Some(Default::default());
}
});
request.replace(Some(GTK_EVENT_HANDLER.request_iteration_start()));
});
}
Self { state }
}
}
impl<R, D> std::future::Future for GtkDialogFuture<R, D> {
type Output = R;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut state = self.state.lock().unwrap();
if state.data.is_some() {
Poll::Ready(state.data.take().unwrap())
} else {
state.waker = Some(cx.waker().clone());
Poll::Pending
}
}
}
use gobject_sys::GCallback;
use gtk_sys::{GtkDialog, GtkResponseType};
use std::ffi::c_void;
use std::os::raw::c_char;
unsafe fn connect_raw<F>(
receiver: *mut gobject_sys::GObject,
signal_name: *const c_char,
trampoline: GCallback,
closure: *mut F,
) {
use std::mem;
use glib_sys::gpointer;
unsafe extern "C" fn destroy_closure<F>(ptr: *mut c_void, _: *mut gobject_sys::GClosure) {
// destroy
Box::<F>::from_raw(ptr as *mut _);
}
assert_eq!(mem::size_of::<*mut F>(), mem::size_of::<gpointer>());
assert!(trampoline.is_some());
let handle = gobject_sys::g_signal_connect_data(
receiver,
signal_name,
trampoline,
closure as *mut _,
Some(destroy_closure::<F>),
0,
);
assert!(handle > 0);
}
unsafe fn connect_response<F: Fn(GtkResponseType) + 'static>(dialog: *mut GtkDialog, f: F) {
use std::mem::transmute;
unsafe extern "C" fn response_trampoline<F: Fn(GtkResponseType) + 'static>(
_this: *mut gtk_sys::GtkDialog,
res: GtkResponseType,
f: glib_sys::gpointer,
) {
let f: &F = &*(f as *const F);
f(res);
}
let f: Box<F> = Box::new(f);
connect_raw(
dialog as *mut _,
b"response\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
response_trampoline::<F> as *const (),
)),
Box::into_raw(f),
);
}
|
pub mod ser {
use std::collections::HashMap;
use itertools::Itertools;
use serde::{
ser::{SerializeMap, SerializeSeq, SerializeStruct},
Serialize, Serializer,
};
use crate::internals::{
query::filter::LayoutFilter,
serialize::{ser::WorldSerializer, UnknownType},
storage::{
archetype::{Archetype, ArchetypeIndex},
component::ComponentTypeId,
UnknownComponentStorage,
},
world::World,
};
pub struct ArchetypeLayoutSerializer<'a, W: WorldSerializer, F: LayoutFilter> {
pub world_serializer: &'a W,
pub world: &'a World,
pub filter: &'a F,
}
impl<'a, W: WorldSerializer, F: LayoutFilter> Serialize for ArchetypeLayoutSerializer<'a, W, F> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let archetypes = self
.world
.archetypes()
.iter()
.filter(|arch| {
self.filter
.matches_layout(arch.layout().component_types())
.is_pass()
})
.collect_vec();
let component_types = archetypes
.iter()
.flat_map(|arch| arch.layout().component_types())
.unique();
let mut type_mappings = HashMap::new();
for id in component_types {
match self.world_serializer.map_id(*id) {
Ok(type_id) => {
type_mappings.insert(*id, type_id);
}
Err(error) => {
match error {
UnknownType::Ignore => {}
UnknownType::Error => {
return Err(serde::ser::Error::custom(format!(
"unknown component type {:?}",
*id
)));
}
}
}
}
}
let mut root = serializer.serialize_seq(Some(archetypes.len()))?;
for archetype in archetypes {
root.serialize_element(&SerializableArchetype {
world_serializer: self.world_serializer,
world: self.world,
type_mappings: &type_mappings,
archetype,
})?;
}
root.end()
}
}
struct SerializableArchetype<'a, W: WorldSerializer> {
world_serializer: &'a W,
world: &'a World,
type_mappings: &'a HashMap<ComponentTypeId, W::TypeId>,
archetype: &'a Archetype,
}
impl<'a, W: WorldSerializer> Serialize for SerializableArchetype<'a, W> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut root = serializer.serialize_struct("archetype", 3)?;
let mut component_type_ids = Vec::new();
let mut component_external_ids = Vec::new();
for type_id in self.archetype.layout().component_types() {
if let Some(mapped) = self.type_mappings.get(type_id) {
component_type_ids.push(*type_id);
component_external_ids.push(mapped);
}
}
root.serialize_field("_layout", &component_external_ids)?;
root.serialize_field("entities", self.archetype.entities())?;
root.serialize_field(
"components",
&SerializableArchetypeComponents {
world_serializer: self.world_serializer,
world: self.world,
component_external_ids,
component_type_ids,
archetype: self.archetype.index(),
},
)?;
root.end()
}
}
struct SerializableArchetypeComponents<'a, W: WorldSerializer> {
world_serializer: &'a W,
world: &'a World,
component_type_ids: Vec<ComponentTypeId>,
component_external_ids: Vec<&'a W::TypeId>,
archetype: ArchetypeIndex,
}
impl<'a, W: WorldSerializer> Serialize for SerializableArchetypeComponents<'a, W> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let components = self.world.components();
let mut root = serializer.serialize_map(Some(self.component_external_ids.len()))?;
for (i, external_id) in self.component_external_ids.iter().enumerate() {
let type_id = self.component_type_ids[i];
root.serialize_entry(
external_id,
&SerializableComponentSlice {
world_serializer: self.world_serializer,
storage: components.get(type_id).unwrap(),
archetype: self.archetype,
type_id,
},
)?;
}
root.end()
}
}
struct SerializableComponentSlice<'a, W: WorldSerializer> {
world_serializer: &'a W,
storage: &'a dyn UnknownComponentStorage,
archetype: ArchetypeIndex,
type_id: ComponentTypeId,
}
impl<'a, W: WorldSerializer> Serialize for SerializableComponentSlice<'a, W> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
unsafe {
self.world_serializer.serialize_component_slice(
self.type_id,
self.storage,
self.archetype,
serializer,
)
}
}
}
}
pub mod de {
use std::{marker::PhantomData, rc::Rc};
use serde::{
de::{DeserializeSeed, MapAccess, SeqAccess, Visitor},
Deserialize, Deserializer,
};
use crate::{
internals::{
serialize::de::WorldDeserializer,
storage::{archetype::EntityLayout, component::ComponentTypeId},
world::World,
},
storage::{ArchetypeSource, ComponentSource, IntoComponentSource, UnknownComponentWriter},
};
pub struct ArchetypeLayoutDeserializer<'a, W: WorldDeserializer> {
pub world_deserializer: &'a W,
pub world: &'a mut World,
}
impl<'a, 'de, W: WorldDeserializer> DeserializeSeed<'de> for ArchetypeLayoutDeserializer<'a, W> {
type Value = ();
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
struct SeqVisitor<'b, S: WorldDeserializer> {
world_deserializer: &'b S,
world: &'b mut World,
}
impl<'b, 'de, S: WorldDeserializer> Visitor<'de> for SeqVisitor<'b, S> {
type Value = ();
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("archetype sequence")
}
fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
where
V: SeqAccess<'de>,
{
while seq
.next_element_seed(DeserializableArchetype {
world_deserializer: self.world_deserializer,
world: self.world,
})?
.is_some()
{}
Ok(())
}
}
deserializer.deserialize_seq(SeqVisitor {
world_deserializer: self.world_deserializer,
world: self.world,
})
}
}
struct DeserializableArchetype<'a, W: WorldDeserializer> {
world_deserializer: &'a W,
world: &'a mut World,
}
impl<'a, 'de, W: WorldDeserializer> DeserializeSeed<'de> for DeserializableArchetype<'a, W> {
type Value = ();
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
struct StructVisitor<'b, S: WorldDeserializer> {
world_deserializer: &'b S,
world: &'b mut World,
}
impl<'b, 'de, S: WorldDeserializer> Visitor<'de> for StructVisitor<'b, S> {
type Value = ();
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("archetype sequence")
}
fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
where
V: SeqAccess<'de>,
{
use serde::de::Error;
let layout = seq
.next_element_seed(LayoutDeserializer {
world_deserializer: self.world_deserializer,
})?
.ok_or_else(|| V::Error::custom("expected archetype layout"))?;
let mut result = None;
self.world.extend(InsertArchetypeSeq {
world_deserializer: self.world_deserializer,
result: &mut result,
seq,
layout: Rc::new(layout),
_phantom: PhantomData,
});
match result.unwrap() {
Ok(_) => Ok(()),
Err(err) => Err(V::Error::custom(err)),
}
}
fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
where
V: MapAccess<'de>,
{
use serde::de::Error;
let layout = if let Some(ArchetypeField::_Layout) = map.next_key()? {
map.next_value_seed(LayoutDeserializer {
world_deserializer: self.world_deserializer,
})
} else {
Err(V::Error::custom("expected archetype layout"))
}?;
let mut result = None;
self.world.extend(InsertArchetypeMap {
world_deserializer: self.world_deserializer,
result: &mut result,
map,
layout: Rc::new(layout),
_phantom: PhantomData,
});
match result.unwrap() {
Ok(_) => Ok(()),
Err(err) => Err(V::Error::custom(err)),
}
}
}
const FIELDS: &[&str] = &["_layout", "entities", "components"];
deserializer.deserialize_struct(
"Archetype",
FIELDS,
StructVisitor {
world_deserializer: self.world_deserializer,
world: self.world,
},
)
}
}
#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "lowercase")]
enum ArchetypeField {
_Layout,
Entities,
Components,
}
struct LayoutDeserializer<'a, W: WorldDeserializer> {
world_deserializer: &'a W,
}
impl<'a, 'de, W: WorldDeserializer> DeserializeSeed<'de> for LayoutDeserializer<'a, W> {
type Value = EntityLayout;
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
struct SeqVisitor<'b, S: WorldDeserializer> {
world_deserializer: &'b S,
}
impl<'b, 'de, S: WorldDeserializer> Visitor<'de> for SeqVisitor<'b, S> {
type Value = EntityLayout;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("type ID sequence")
}
fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
where
V: SeqAccess<'de>,
{
let mut layout = EntityLayout::new();
while let Some(mapped_type_id) = seq.next_element::<S::TypeId>()? {
self.world_deserializer
.register_component(mapped_type_id, &mut layout);
}
Ok(layout)
}
}
deserializer.deserialize_seq(SeqVisitor {
world_deserializer: self.world_deserializer,
})
}
}
struct InsertArchetypeSeq<'a, 'de, W: WorldDeserializer, V: SeqAccess<'de>> {
world_deserializer: &'a W,
seq: V,
result: &'a mut Option<Result<(), String>>,
layout: Rc<EntityLayout>,
_phantom: PhantomData<&'de ()>,
}
impl<'a, 'de, W: WorldDeserializer, V: SeqAccess<'de>> InsertArchetypeSeq<'a, 'de, W, V> {
fn deserialize<'w>(
&mut self,
writer: &mut crate::storage::ArchetypeWriter<'w>,
) -> Result<(), V::Error> {
use serde::de::Error;
self.seq
.next_element_seed(EntitySeq { writer })?
.ok_or_else(|| V::Error::custom("expected entity seq"))?;
self.seq
.next_element_seed(ComponentMap {
writer,
world_deserializer: self.world_deserializer,
})?
.ok_or_else(|| V::Error::custom("expected component map"))?;
Ok(())
}
}
impl<'a, 'de, W: WorldDeserializer, V: SeqAccess<'de>> ArchetypeSource
for InsertArchetypeSeq<'a, 'de, W, V>
{
type Filter = Rc<EntityLayout>;
fn filter(&self) -> Self::Filter {
self.layout.clone()
}
fn layout(&mut self) -> EntityLayout {
(*self.layout).clone()
}
}
impl<'a, 'de, W: WorldDeserializer, V: SeqAccess<'de>> ComponentSource
for InsertArchetypeSeq<'a, 'de, W, V>
{
fn push_components<'c>(
&mut self,
writer: &mut crate::storage::ArchetypeWriter<'c>,
_: impl Iterator<Item = crate::Entity>,
) {
*self.result = match self.deserialize(writer) {
Ok(_) => Some(Ok(())),
Err(err) => Some(Err(err.to_string())),
}
}
}
impl<'a, 'de, W: WorldDeserializer, V: SeqAccess<'de>> IntoComponentSource
for InsertArchetypeSeq<'a, 'de, W, V>
{
type Source = Self;
fn into(self) -> Self::Source {
self
}
}
struct InsertArchetypeMap<'a, 'de, W: WorldDeserializer, V: MapAccess<'de>> {
world_deserializer: &'a W,
map: V,
result: &'a mut Option<Result<(), String>>,
layout: Rc<EntityLayout>,
_phantom: PhantomData<&'de ()>,
}
impl<'a, 'de, W: WorldDeserializer, V: MapAccess<'de>> InsertArchetypeMap<'a, 'de, W, V> {
fn deserialize<'w>(
&mut self,
writer: &mut crate::storage::ArchetypeWriter<'w>,
) -> Result<(), V::Error> {
use serde::de::Error;
while let Some(key) = self.map.next_key()? {
match key {
ArchetypeField::Entities => self.map.next_value_seed(EntitySeq { writer })?,
ArchetypeField::Components => {
self.map.next_value_seed(ComponentMap {
writer,
world_deserializer: self.world_deserializer,
})?
}
_ => return Err(V::Error::custom("unexpected field")),
}
}
Ok(())
}
}
impl<'a, 'de, W: WorldDeserializer, V: MapAccess<'de>> ArchetypeSource
for InsertArchetypeMap<'a, 'de, W, V>
{
type Filter = Rc<EntityLayout>;
fn filter(&self) -> Self::Filter {
self.layout.clone()
}
fn layout(&mut self) -> EntityLayout {
(*self.layout).clone()
}
}
impl<'a, 'de, W: WorldDeserializer, V: MapAccess<'de>> ComponentSource
for InsertArchetypeMap<'a, 'de, W, V>
{
fn push_components<'c>(
&mut self,
writer: &mut crate::storage::ArchetypeWriter<'c>,
_: impl Iterator<Item = crate::Entity>,
) {
*self.result = match self.deserialize(writer) {
Ok(_) => Some(Ok(())),
Err(err) => Some(Err(err.to_string())),
}
}
}
impl<'a, 'de, W: WorldDeserializer, V: MapAccess<'de>> IntoComponentSource
for InsertArchetypeMap<'a, 'de, W, V>
{
type Source = Self;
fn into(self) -> Self::Source {
self
}
}
struct EntitySeq<'a, 'b> {
writer: &'a mut crate::storage::ArchetypeWriter<'b>,
}
impl<'a, 'b, 'de> DeserializeSeed<'de> for EntitySeq<'a, 'b> {
type Value = ();
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
struct SeqVisitor<'c, 'd> {
writer: &'c mut crate::storage::ArchetypeWriter<'d>,
}
impl<'c, 'd, 'de> Visitor<'de> for SeqVisitor<'c, 'd> {
type Value = ();
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("entity seq")
}
fn visit_seq<V>(self, mut seq: V) -> Result<Self::Value, V::Error>
where
V: SeqAccess<'de>,
{
if let Some(len) = seq.size_hint() {
self.writer.reserve(len);
}
while let Some(entity) = seq.next_element()? {
self.writer.push(entity);
}
Ok(())
}
}
deserializer.deserialize_seq(SeqVisitor {
writer: self.writer,
})
}
}
struct ComponentMap<'a, 'b, W: WorldDeserializer> {
writer: &'a mut crate::storage::ArchetypeWriter<'b>,
world_deserializer: &'a W,
}
impl<'a, 'b, 'de, W: WorldDeserializer> DeserializeSeed<'de> for ComponentMap<'a, 'b, W> {
type Value = ();
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
struct MapVisitor<'c, 'd, S: WorldDeserializer> {
writer: &'c mut crate::storage::ArchetypeWriter<'d>,
world_deserializer: &'c S,
}
impl<'c, 'd, 'de, S: WorldDeserializer> Visitor<'de> for MapVisitor<'c, 'd, S> {
type Value = ();
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("component map")
}
fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
where
V: MapAccess<'de>,
{
while let Some(external_type_id) = map.next_key::<S::TypeId>()? {
if let Ok(type_id) = self.world_deserializer.unmap_id(&external_type_id) {
let storage = self.writer.claim_components_unknown(type_id);
map.next_value_seed(ComponentSlice {
storage,
type_id,
world_deserializer: self.world_deserializer,
})?;
}
}
Ok(())
}
}
deserializer.deserialize_map(MapVisitor {
world_deserializer: self.world_deserializer,
writer: self.writer,
})
}
}
struct ComponentSlice<'a, 'b, W: WorldDeserializer> {
storage: UnknownComponentWriter<'b>,
type_id: ComponentTypeId,
world_deserializer: &'a W,
}
impl<'a, 'b, 'de, W: WorldDeserializer> DeserializeSeed<'de> for ComponentSlice<'a, 'b, W> {
type Value = ();
fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
self.world_deserializer.deserialize_component_slice(
self.type_id,
self.storage,
deserializer,
)
}
}
}
|
use nutype::nutype;
use std::ops::Add;
use crate::{format_string, Error};
const MM_PER_INCH: f64 = 25.4;
/// Precipitation in mm
#[nutype(validate(min=0.0))]
#[derive(*, Serialize, Deserialize)]
pub struct Precipitation(f64);
impl Default for Precipitation {
fn default() -> Self {
Self::new(0.0).unwrap()
}
}
impl Add for Precipitation {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Self::new(self.into_inner().add(rhs.into_inner())).unwrap()
}
}
impl Precipitation {
/// ```
/// use weather_util_rust::precipitation::Precipitation;
/// # use anyhow::Error;
/// # fn main() -> Result<(), Error> {
/// let rain = Precipitation::from_inches(1.0)?;
/// assert_eq!(rain.millimeters(), 25.4);
/// # Ok(())
/// # }
/// ```
/// # Errors
///
/// Will return error if input is less than zero
pub fn from_millimeters(precip: f64) -> Result<Self, Error> {
Self::new(precip).map_err(|e| Error::InvalidValue(format_string!("{e}")))
}
/// # Errors
///
/// Will return error if input is less than zero
pub fn from_inches(precip: f64) -> Result<Self, Error> {
Self::new(precip * MM_PER_INCH).map_err(|e| Error::InvalidValue(format_string!("{e}")))
}
#[inline]
#[must_use]
pub fn millimeters(self) -> f64 {
self.into_inner()
}
#[inline]
#[must_use]
pub fn inches(self) -> f64 {
self.into_inner() / MM_PER_INCH
}
}
#[cfg(test)]
mod test {
use std::convert::TryFrom;
use crate::{
format_string,
precipitation::{Precipitation, MM_PER_INCH},
Error,
};
#[test]
fn test_precipitation() -> Result<(), Error> {
let p = Precipitation::new(1.0).map_err(|e| Error::InvalidValue(format_string!("{e}")))?;
assert_eq!(p.millimeters(), 1.0);
assert_eq!(p.inches(), 1.0 / MM_PER_INCH);
let p2 = Precipitation::from_millimeters(1.0)?;
assert_eq!(p, p2);
let p = Precipitation::from_inches(1.0)?;
assert_eq!(p.inches(), 1.0);
let h = Precipitation::try_from(-1.0);
assert!(h.is_err());
Ok(())
}
}
|
use std::rc::Rc;
use scheme::errors::EvalErr;
use scheme::eval::eval;
use scheme::parser::parse_expression;
use scheme::scope::Scope;
use scheme::{eval_expr, eval_file};
fn assert_eval(expr: &str, expected: &str) {
assert_eval_with_scope(&Rc::new(Scope::from_global()), expr, expected);
}
fn assert_eval_with_scope(scope: &Rc<Scope>, expr: &str, expected: &str) {
let obj = parse_expression(expr).unwrap().pop().unwrap();
match eval(&Rc::new(obj), &scope) {
Ok(obj) => assert_eq!(format!("{}", obj), expected),
Err(err) => panic!("{}", err),
}
}
fn expect_err(expr: &str, expected: EvalErr) {
let scope = Scope::from_global();
let obj = parse_expression(expr).unwrap().pop().unwrap();
let result = eval(&Rc::new(obj), &Rc::new(scope));
match result {
Ok(_) => panic!(
"expression {} expected to evaluate with the error\n\"{}\"",
expr, expected
),
Err(err) => {
if err != expected {
panic!(
"expression \"{}\" expected to evaluate with the error\n\"{}\" but the actual error is \n\"{}\"",
expr, expected, err
);
}
}
}
}
#[test]
#[rustfmt::skip]
fn core_functions() {
assert_eval("(begin 1 2 3)", "3");
assert_eval("'1", "1");
assert_eval("'''foo", "(quote (quote foo))");
expect_err("(list a)", EvalErr::UnboundVariable("a".to_string()));
expect_err("(begin 1 . 2)", EvalErr::ListRequired("(1 . 2)".to_string()));
expect_err("(quote 1 2)", EvalErr::WrongAgrsNum("quote".to_string(), 1, 2));
}
#[test]
#[rustfmt::skip]
fn lists_and_pairs() {
assert_eval("(car '(1 . 2))", "1");
assert_eval("(cdr '(1 . 2))", "2");
assert_eval("(car (cdr '(1 2 3)))", "2");
assert_eval("(cadr '(1 2 3))", "2");
assert_eval("(cadar '((1 2) 3))", "2");
assert_eval("(cddr '(1 2 3))", "(3)");
assert_eval("(caaaar '((((1 2 3))) 4))", "1");
expect_err ("(caaaaar '())", EvalErr::UnboundVariable("caaaaar".to_string()));
assert_eval("(length '(1 2 3))", "3");
assert_eval("(cons 1 2)", "(1 . 2)");
assert_eval("(cons 1 '(2 3))", "(1 2 3)");
assert_eval("(list 1 2 3)", "(1 2 3)");
expect_err("(car 5)", EvalErr::PairRequired("5".to_string()));
}
#[test]
#[rustfmt::skip]
fn let_and_define() {
assert_eval("(begin (define x 5) (cons (begin (define x 2) x) x))", "(2 . 2)");
assert_eval("(begin (define (x a) (car a)) (x '(5 6)))", "5");
assert_eval("(begin (define (tail a . b) b) (tail 1 2 3))", "(2 3)");
expect_err("(define 5)", EvalErr::WrongDefineArgument("5".to_string()));
expect_err("(define (5))", EvalErr::ExpectedSymbolForFunctionName("5".to_string()));
expect_err("(define (f x))", EvalErr::EmptyFunctionBody());
}
#[test]
#[rustfmt::skip]
fn lambda() {
// lambda functions
assert_eval("((lambda x x) 1 2 3)", "(1 2 3)");
assert_eval("((lambda (x . y) y) 1 2 3)", "(2 3)");
assert_eval("(begin (define f (lambda (x) x)) (f 'foo))", "foo");
expect_err("(lambda (1) a)", EvalErr::ExpectedSymbolForArgument("1".to_string()));
expect_err("(lambda (x x) x)", EvalErr::ArgumentDuplication("x".to_string()));
expect_err("((lambda (a b) a) 1)", EvalErr::TooFewArguments("#<lambda>".to_string()));
expect_err("((lambda (a b) a) 1 2 3)", EvalErr::TooManyArguments("#<lambda>".to_string()));
expect_err("(5)", EvalErr::IllegalObjectAsAFunction("5".to_string()));
}
#[test]
#[rustfmt::skip]
fn logic_functions() {
assert_eval("(or 5 foo #f)", "5");
expect_err("(or #f foo)", EvalErr::UnboundVariable("foo".to_string()));
assert_eval("(and 5 'foo 42)", "42");
assert_eval("(list (boolean? #f) (boolean? 5))", "(#t #f)");
assert_eval("(list (null? #t) (null? '(5)) (null? '()) (null? (cdr '(5))))", "(#f #f #t #t)");
assert_eval("(list (pair? '(1 2)) (pair? 5))", "(#t #f)");
assert_eval("(list (list? '(1 2)) (list? 5) (list? '(1 . 2)))", "(#t #f #f)");
assert_eval("(list (not #f) (not 5))", "(#t #f)");
}
#[test]
#[rustfmt::skip]
fn if_cond() {
assert_eval("(if #t 1 2)", "1");
assert_eval("(if #f 1 2)", "2");
assert_eval("(cond (#f 42) ('foo))", "foo");
assert_eval("(cond (#f 42) (5 'foo))", "foo");
assert_eval("(cond (#f 42))", "#<undef>");
assert_eval("(cond (#f 42) (else))", "#<undef>");
assert_eval("(cond (#f 42) (else 1 2))", "2");
assert_eval("(cond (#f 42) (#t 1 2))", "2");
expect_err("(cond)", EvalErr::CondNeedsClause());
expect_err("(cond ())", EvalErr::CondEmptyClause());
}
#[test]
#[rustfmt::skip]
fn test_math() {
assert_eval("(list (number? 1) (number? 'foo))", "(#t #f)");
assert_eval("(list (integer? 1) (integer? 1.0))", "(#t #f)");
assert_eval("(list (real? 1) (real? 1.0))", "(#t #t)");
assert_eval("(list (= 1 1 2) (= 1 1.0))", "(#f #t)");
assert_eval("(list (< 1 2.0 3) (< 1 3 2))", "(#t #f)");
assert_eval("(list (> 5 3 0) (> 5 1.0 3))", "(#t #f)");
assert_eval("(list (+) (+ 1) (+ 1 2 3) (+ 1 2 3.5))", "(0 1 6 6.5)");
assert_eval("(list (-) (- 1) (- 1 2.5) (- 1 2 3))", "(0 -1 -1.5 -4)");
assert_eval("(list (*) (* 2) (* 1 2 3.5))", "(1 2 7)");
assert_eval("(list (/) (/ 2) (/ 2 1))", "(1 0.5 2)");
assert_eval("(integer? (/ (+ 3 5) (* 1 2)))", "#t");
assert_eval("(integer? (/ (+ 3 4) (* 1 2)))", "#f");
assert_eval("(list (quotient 13 4) (quotient -13 4) (quotient 13 -4) (quotient -13 -4))", "(3 -3 -3 3)");
assert_eval("(list (remainder 13 4) (remainder -13 4) (remainder 13 -4) (remainder -13 -4))", "(1 -1 1 -1)");
assert_eval("(list (modulo 13 4) (modulo -13 4) (modulo 13 -4) (modulo -13 -4))", "(1 3 -3 -1)");
expect_err("(= 1 foo)", EvalErr::UnboundVariable("foo".to_string()));
expect_err("(+ 1 'foo)", EvalErr::NumericArgsRequiredFor("+".to_string()));
expect_err("(/ 1 2 0)", EvalErr::DivisionByZero());
expect_err("(modulo 13.5 4)", EvalErr::IntegerArgsRequiredFor("modulo".to_string()));
}
#[test]
#[rustfmt::skip]
fn apply_and_map() {
assert_eval("(apply list '(1 2 3))", "(1 2 3)");
assert_eval("(apply list 1 2 '(3 4))", "(1 2 3 4)");
assert_eval("(apply list 1 (+ 1 1) '(3 (+ 2 2)))", "(1 2 3 (+ 2 2))");
assert_eval("(let ((foo (lambda (x) (+ x 10)))) (apply foo '(0)))", "10");
expect_err("(apply + 1 2 3)", EvalErr::ApplyNeedsProperList("3".to_string()));
expect_err("(apply +)", EvalErr::NeedAtLeastArgs("apply".to_string(), 2, 1));
assert_eval("(map list '(1 2 3))", "((1) (2) (3))");
assert_eval("(map list '(1 2 (+ 1 2)))", "((1) (2) ((+ 1 2)))");
assert_eval("(map list '(1 2 3) '(4 5 6))", "((1 4) (2 5) (3 6))");
expect_err("(map + '(1 2) '(4 5 6))", EvalErr::UnequalMapLists());
expect_err("(map +)", EvalErr::NeedAtLeastArgs("map".to_string(), 2, 1));
assert_eval("(map (lambda (x, y) (+ x y)) '())", "()");
}
#[test]
#[rustfmt::skip]
fn equalities() {
assert_eval("(list (eqv? '() '()) (eqv? '(a) '(a)) (eqv? '(()) '(())))", "(#t #f #f)");
assert_eval("(list (eqv? #t #t) (eqv? #t #f) (eqv? #t 42))", "(#t #f #f)");
assert_eval("(list (eqv? 'a 'a) (eqv? 'a 'b))", "(#t #f)");
assert_eval("(eqv? (lambda () 1) (lambda () 1))", "#f");
assert_eval("(let ((p (lambda (x) x))) (eqv? p p))", "#t");
assert_eval("(let ((a '(a)) (b '(a))) (list (eqv? a a) (eqv? a b)))", "(#t #f)");
assert_eval("(let ((a '(a b))) (eqv? (cdr a) (cdr a)))", "#t");
assert_eval("(let ((a '(a b))) (eqv? (cdr a) '(b)))", "#f");
assert_eval("(eqv? car car)", "#t");
assert_eval("(eqv? cdadar cdadar)", "#t");
assert_eval("(list (eqv? 2 2) (eqv? 2 3) (eqv? 2 2.0))", "(#t #f #t)");
assert_eval("(list (eq? 2 2) (eq? 2 3) (eq? 2 2.0))", "(#t #f #f)");
assert_eval("(equal? '(a b (c)) '(a b (c)))", "#t");
assert_eval("(equal? '(a b (c)) '(a b c))", "#f");
assert_eval("(equal? '(a b (c)) '(a b))", "#f");
assert_eval("(equal? '(2) '(2.0))", "#t");
}
#[test]
#[rustfmt::skip]
fn prelude() {
let scope = &Rc::new(Scope::from_global());
assert!(eval_file("prelude.scm", scope).is_ok());
assert_eval_with_scope(scope, "(foldr cons '() '(1 2 3))", "(1 2 3)");
assert_eval_with_scope(scope, "(foldl cons '() '(1 2 3))", "(((() . 1) . 2) . 3)");
assert_eval_with_scope(scope, "(append '(1 2) '(3 4))", "(1 2 3 4)");
assert_eval_with_scope(scope, "(reverse '(1 2 3 4))", "(4 3 2 1)");
}
#[test]
#[rustfmt::skip]
fn test_let() {
assert_eval("(let ((x 2)) x)", "2");
assert_eval("(let ((x car) (y '(1 2 3))) (x y))", "1");
assert_eval("(let ((x 11)) (let ((x 22) (y x)) y))", "11");
assert_eval("(let ((x 11)) (let* ((x 22) (y x)) y))", "22");
expect_err("(let ((z 22) (y z)) y)", EvalErr::UnboundVariable("z".to_string()));
assert_eval("(let* ((z 22) (y z)) y)", "22");
let body = "((fun (lambda () fun))) (fun)";
expect_err(&format!("(let {})", body), EvalErr::UnboundVariable("fun".to_string()));
assert_eval(&format!("(letrec {})", body), "<function>");
assert_eval("(let ((x 2)) (map (lambda (y) (+ x y)) '(1 2 3)))", "(3 4 5)");
assert_eval("(let ((f (lambda (y) (+ y 2)))) (map f '(1 2 3)))", "(3 4 5)");
assert_eval("(let ((x (lambda () '(1 2 3)))) (map + (x) (x)))", "(2 4 6)");
assert_eval("
(letrec
((fib (lambda (n) (if (< n 2) 1 (+ (fib1 n) (fib2 n)))))
(fib1 (lambda (n) (fib (- n 1))))
(fib2 (lambda (n) (fib (- n 2))))
(x (fib 10)))
x)", "89");
}
#[test]
#[rustfmt::skip]
/// Verifies that tail calls are working properly.
/// That is, tail recursion does not lead to stack overflow.
fn test_tail_call() {
let scope = &Rc::new(Scope::from_global());
// sum of 10000 consecutive integers
let seq_sum = "
(define (seq-sum n)
(define (seq-sum n acc)
(if (= 0 n) acc (seq-sum (- n 1) (+ acc n))))
(seq-sum n 0))";
eval_expr(seq_sum, scope).unwrap();
assert_eval_with_scope(scope, "(seq-sum 10000)", "50005000");
// mutual recursion
let is_odd = "
(define (odd? n)
(if (= n 0) #f (even? (- n 1))))";
let is_even = "
(define (even? n)
(if (= n 0) #t (odd? (- n 1))))";
eval_expr(is_odd, scope).unwrap();
eval_expr(is_even, scope).unwrap();
assert_eval_with_scope(scope, "(map even? '(10500 9999))", "(#t #f)");
// tail recursion with 'apply'
let seq_sum = "
(define (seq-sum n)
(define (seq-sum n acc)
(if (= 0 n) acc (apply seq-sum (list (- n 1) (+ acc n)))))
(seq-sum n 0))";
eval_expr(seq_sum, scope).unwrap();
assert_eval_with_scope(scope, "(seq-sum 10000)", "50005000");
}
|
//! inversion engine serialization codec
use crate::inv_any::*;
use crate::inv_api_spec::*;
use crate::inv_error::*;
use crate::inv_uniq::*;
/// Serialization codec for InversionApi Events.
/// Both sides can emit these events, both sides can receive them.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum InvApiCodecEvt {
/// Notify the remote end of a new local ImplSpec
/// On new binding, both sides should emit events of this
/// type for all pre-existing local specs.
NewImplSpec {
/// the ImplSpec
impl_spec: ImplSpec,
},
/// a bus message from a bound protocol
BoundMessage {
/// the uniq id associated with this binding
binding_id: InvUniq,
/// the msg_id for this specific message
msg_id: InvUniq,
/// the data content of this message
data: InvAny,
},
}
/// Serialization codec for InversionApi Requests and Responses.
/// Both sides can send all requests and responses,
/// both sides can receive all requests and responses.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum InvApiCodecReqRes {
/// A process local to the sender of this message is requesting
/// to bind to an Impl on the receiver of this message.
NewImplBindingReq {
/// a uniq id to use for messages related to this binding
binding_id: InvUniq,
/// the impl id to bind to
impl_id: ImplSpecId,
},
/// if the binding was successful, return this message
NewImplBindingRes {
/// the uniq binding_id sent with the Req
binding_id: InvUniq,
/// if None, the result was a success.
/// if Some, the result of the binding was an error.
error: Option<InvError>,
},
}
/*
use futures::future::{BoxFuture, FutureExt};
use futures::sink::SinkExt;
use parking_lot::Mutex;
use std::future::Future;
use std::sync::Arc;
/// Helper traits. You probably don't need this unless you are implementing a
/// custom inversion engine serialization codec.
pub mod traits {
use super::*;
/// Establish a message bus between a local InvBroker and a remote.
/// This is the sending side.
pub trait AsInvCodecSender: 'static + Send + Sync {
/// Notify the remote end of a new local ImplSpec
fn new_impl_spec(
&self,
impl_spec: ImplSpec,
) -> BoxFuture<'static, InvResult<()>>;
}
/// Establish a message bus between a local InvBroker and a remote.
/// This is the handler side.
pub trait AsInvCodecHandler: 'static + Send {}
}
use traits::*;
impl InvCodecMessage {
/// Serialize
pub fn encode(self) -> Vec<u8> {
use serde::Serialize;
let mut se = rmp_serde::encode::Serializer::new(Vec::new())
.with_struct_map()
.with_string_variants();
self.serialize(&mut se).expect("failed serialize");
se.into_inner()
}
}
/// Establish a message bus between a local InvBroker and a remote InvBroker.
/// This is the sending side.
#[derive(Clone)]
pub struct InvCodecSender(Arc<dyn AsInvCodecSender>);
impl InvCodecSender {
/// Notify the remote end of a new local ImplSpec
pub fn new_impl_spec(
&self,
impl_spec: ImplSpec,
) -> impl Future<Output = InvResult<()>> + 'static + Send {
AsInvCodecSender::new_impl_spec(&*self.0, impl_spec)
}
}
/// Establish a message bus between a local InvBroker and a remote InvBroker.
/// This is the handler side.
pub struct InvCodecHandler(Box<dyn AsInvCodecHandler>);
impl InvCodecHandler {
/*
/// Handle incoming codec messages.
pub fn handle<
NewImplSpecCb
>(self: Box<Self>, _new_impl_spec_cb: NewImplSpecCb)
where
NewImplSpecCb: Fn(ImplSpec)
*/
}
/// Create a codec message bus between a local InvBroker and a remote InvBroker.
pub fn inv_codec<R, W>(r: R, w: W) -> (InvCodecSender, InvCodecHandler)
where
R: tokio::io::AsyncRead + 'static + Send,
W: tokio::io::AsyncWrite + 'static + Send + Unpin,
{
use tokio_util::codec::*;
let mut builder = LengthDelimitedCodec::builder();
builder.little_endian();
let _r = builder.new_read(r);
let w = builder.new_write(w);
struct S<W>
where
W: tokio::io::AsyncWrite + 'static + Send + Unpin,
{
limit: Arc<tokio::sync::Semaphore>,
inner: Arc<Mutex<Option<FramedWrite<W, LengthDelimitedCodec>>>>,
}
impl<W> AsInvCodecSender for S<W>
where
W: tokio::io::AsyncWrite + 'static + Send + Unpin,
{
fn new_impl_spec(
&self,
impl_spec: ImplSpec,
) -> BoxFuture<'static, InvResult<()>> {
let limit = self.limit.clone();
let inner = self.inner.clone();
async move {
let _permit = limit
.clone()
.acquire_owned()
.await
.map_err(InvError::other)?;
// if we have a permit, the sender is available
let mut raw_send = inner.lock().take().unwrap();
//let uniq = InvUniq::new_rand();
// TODO - register this uniq so we can reference later
let encoded = InvCodecMessage::NewImplSpec {
//ref_id: uniq,
impl_spec,
}
.encode();
let res = raw_send
.send(encoded.into())
.await
.map_err(InvError::other);
*(inner.lock()) = Some(raw_send);
// TODO - on error close the channel
res
}
.boxed()
}
}
let s = InvCodecSender(Arc::new(S {
limit: Arc::new(tokio::sync::Semaphore::new(1)),
inner: Arc::new(Mutex::new(Some(w))),
}));
struct H;
impl AsInvCodecHandler for H {}
let h = InvCodecHandler(Box::new(H));
(s, h)
}
*/
|
#![allow(unused_must_use)]
#![no_main]
#![feature(start)]
mod ns;
mod olintest;
mod regression;
mod scheme;
use log::error;
use olin::{entrypoint, runtime::exit};
use std::io::Error;
entrypoint!();
fn main() -> Result<(), std::io::Error> {
let mut fail_count = 0;
let funcs = [
ns::env::test,
ns::random::test,
ns::resource::test,
ns::runtime::test,
ns::startup::test,
ns::stdio::test,
ns::time::test,
olintest::http::test,
regression::issue22::test,
regression::issue37::test,
regression::issue39::test,
//scheme::gemini::test,
scheme::http::test,
scheme::log::test,
scheme::null::test,
scheme::random::test,
scheme::zero::test,
];
for func in &funcs {
match func() {
Ok(()) => {}
Err(e) => {
error!("test error: {:?}", e);
fail_count += 1;
}
}
}
exit(fail_count);
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtWidgets/qgraphicslayout.h
// dst-file: /src/widgets/qgraphicslayout.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::qgraphicslayoutitem::*; // 773
use std::ops::Deref;
use super::super::core::qcoreevent::*; // 771
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QGraphicsLayout_Class_Size() -> c_int;
// proto: void QGraphicsLayout::updateGeometry();
fn C_ZN15QGraphicsLayout14updateGeometryEv(qthis: u64 /* *mut c_void*/);
// proto: bool QGraphicsLayout::isActivated();
fn C_ZNK15QGraphicsLayout11isActivatedEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QGraphicsLayout::invalidate();
fn C_ZN15QGraphicsLayout10invalidateEv(qthis: u64 /* *mut c_void*/);
// proto: void QGraphicsLayout::removeAt(int index);
fn C_ZN15QGraphicsLayout8removeAtEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: QGraphicsLayoutItem * QGraphicsLayout::itemAt(int i);
fn C_ZNK15QGraphicsLayout6itemAtEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> *mut c_void;
// proto: void QGraphicsLayout::getContentsMargins(qreal * left, qreal * top, qreal * right, qreal * bottom);
fn C_ZNK15QGraphicsLayout18getContentsMarginsEPdS0_S0_S0_(qthis: u64 /* *mut c_void*/, arg0: *mut c_double, arg1: *mut c_double, arg2: *mut c_double, arg3: *mut c_double);
// proto: void QGraphicsLayout::setContentsMargins(qreal left, qreal top, qreal right, qreal bottom);
fn C_ZN15QGraphicsLayout18setContentsMarginsEdddd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double);
// proto: void QGraphicsLayout::widgetEvent(QEvent * e);
fn C_ZN15QGraphicsLayout11widgetEventEP6QEvent(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: static bool QGraphicsLayout::instantInvalidatePropagation();
fn C_ZN15QGraphicsLayout28instantInvalidatePropagationEv() -> c_char;
// proto: static void QGraphicsLayout::setInstantInvalidatePropagation(bool enable);
fn C_ZN15QGraphicsLayout31setInstantInvalidatePropagationEb(arg0: c_char);
// proto: void QGraphicsLayout::~QGraphicsLayout();
fn C_ZN15QGraphicsLayoutD2Ev(qthis: u64 /* *mut c_void*/);
// proto: void QGraphicsLayout::activate();
fn C_ZN15QGraphicsLayout8activateEv(qthis: u64 /* *mut c_void*/);
// proto: int QGraphicsLayout::count();
fn C_ZNK15QGraphicsLayout5countEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QGraphicsLayout::QGraphicsLayout(QGraphicsLayoutItem * parent);
fn C_ZN15QGraphicsLayoutC2EP19QGraphicsLayoutItem(arg0: *mut c_void) -> u64;
} // <= ext block end
// body block begin =>
// class sizeof(QGraphicsLayout)=1
#[derive(Default)]
pub struct QGraphicsLayout {
qbase: QGraphicsLayoutItem,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QGraphicsLayout {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QGraphicsLayout {
return QGraphicsLayout{qbase: QGraphicsLayoutItem::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QGraphicsLayout {
type Target = QGraphicsLayoutItem;
fn deref(&self) -> &QGraphicsLayoutItem {
return & self.qbase;
}
}
impl AsRef<QGraphicsLayoutItem> for QGraphicsLayout {
fn as_ref(& self) -> & QGraphicsLayoutItem {
return & self.qbase;
}
}
// proto: void QGraphicsLayout::updateGeometry();
impl /*struct*/ QGraphicsLayout {
pub fn updateGeometry<RetType, T: QGraphicsLayout_updateGeometry<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.updateGeometry(self);
// return 1;
}
}
pub trait QGraphicsLayout_updateGeometry<RetType> {
fn updateGeometry(self , rsthis: & QGraphicsLayout) -> RetType;
}
// proto: void QGraphicsLayout::updateGeometry();
impl<'a> /*trait*/ QGraphicsLayout_updateGeometry<()> for () {
fn updateGeometry(self , rsthis: & QGraphicsLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGraphicsLayout14updateGeometryEv()};
unsafe {C_ZN15QGraphicsLayout14updateGeometryEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: bool QGraphicsLayout::isActivated();
impl /*struct*/ QGraphicsLayout {
pub fn isActivated<RetType, T: QGraphicsLayout_isActivated<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isActivated(self);
// return 1;
}
}
pub trait QGraphicsLayout_isActivated<RetType> {
fn isActivated(self , rsthis: & QGraphicsLayout) -> RetType;
}
// proto: bool QGraphicsLayout::isActivated();
impl<'a> /*trait*/ QGraphicsLayout_isActivated<i8> for () {
fn isActivated(self , rsthis: & QGraphicsLayout) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QGraphicsLayout11isActivatedEv()};
let mut ret = unsafe {C_ZNK15QGraphicsLayout11isActivatedEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QGraphicsLayout::invalidate();
impl /*struct*/ QGraphicsLayout {
pub fn invalidate<RetType, T: QGraphicsLayout_invalidate<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.invalidate(self);
// return 1;
}
}
pub trait QGraphicsLayout_invalidate<RetType> {
fn invalidate(self , rsthis: & QGraphicsLayout) -> RetType;
}
// proto: void QGraphicsLayout::invalidate();
impl<'a> /*trait*/ QGraphicsLayout_invalidate<()> for () {
fn invalidate(self , rsthis: & QGraphicsLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGraphicsLayout10invalidateEv()};
unsafe {C_ZN15QGraphicsLayout10invalidateEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QGraphicsLayout::removeAt(int index);
impl /*struct*/ QGraphicsLayout {
pub fn removeAt<RetType, T: QGraphicsLayout_removeAt<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.removeAt(self);
// return 1;
}
}
pub trait QGraphicsLayout_removeAt<RetType> {
fn removeAt(self , rsthis: & QGraphicsLayout) -> RetType;
}
// proto: void QGraphicsLayout::removeAt(int index);
impl<'a> /*trait*/ QGraphicsLayout_removeAt<()> for (i32) {
fn removeAt(self , rsthis: & QGraphicsLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGraphicsLayout8removeAtEi()};
let arg0 = self as c_int;
unsafe {C_ZN15QGraphicsLayout8removeAtEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QGraphicsLayoutItem * QGraphicsLayout::itemAt(int i);
impl /*struct*/ QGraphicsLayout {
pub fn itemAt<RetType, T: QGraphicsLayout_itemAt<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.itemAt(self);
// return 1;
}
}
pub trait QGraphicsLayout_itemAt<RetType> {
fn itemAt(self , rsthis: & QGraphicsLayout) -> RetType;
}
// proto: QGraphicsLayoutItem * QGraphicsLayout::itemAt(int i);
impl<'a> /*trait*/ QGraphicsLayout_itemAt<QGraphicsLayoutItem> for (i32) {
fn itemAt(self , rsthis: & QGraphicsLayout) -> QGraphicsLayoutItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QGraphicsLayout6itemAtEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZNK15QGraphicsLayout6itemAtEi(rsthis.qclsinst, arg0)};
let mut ret1 = QGraphicsLayoutItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QGraphicsLayout::getContentsMargins(qreal * left, qreal * top, qreal * right, qreal * bottom);
impl /*struct*/ QGraphicsLayout {
pub fn getContentsMargins<RetType, T: QGraphicsLayout_getContentsMargins<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.getContentsMargins(self);
// return 1;
}
}
pub trait QGraphicsLayout_getContentsMargins<RetType> {
fn getContentsMargins(self , rsthis: & QGraphicsLayout) -> RetType;
}
// proto: void QGraphicsLayout::getContentsMargins(qreal * left, qreal * top, qreal * right, qreal * bottom);
impl<'a> /*trait*/ QGraphicsLayout_getContentsMargins<()> for (&'a mut Vec<f64>, &'a mut Vec<f64>, &'a mut Vec<f64>, &'a mut Vec<f64>) {
fn getContentsMargins(self , rsthis: & QGraphicsLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QGraphicsLayout18getContentsMarginsEPdS0_S0_S0_()};
let arg0 = self.0.as_ptr() as *mut c_double;
let arg1 = self.1.as_ptr() as *mut c_double;
let arg2 = self.2.as_ptr() as *mut c_double;
let arg3 = self.3.as_ptr() as *mut c_double;
unsafe {C_ZNK15QGraphicsLayout18getContentsMarginsEPdS0_S0_S0_(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: void QGraphicsLayout::setContentsMargins(qreal left, qreal top, qreal right, qreal bottom);
impl /*struct*/ QGraphicsLayout {
pub fn setContentsMargins<RetType, T: QGraphicsLayout_setContentsMargins<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setContentsMargins(self);
// return 1;
}
}
pub trait QGraphicsLayout_setContentsMargins<RetType> {
fn setContentsMargins(self , rsthis: & QGraphicsLayout) -> RetType;
}
// proto: void QGraphicsLayout::setContentsMargins(qreal left, qreal top, qreal right, qreal bottom);
impl<'a> /*trait*/ QGraphicsLayout_setContentsMargins<()> for (f64, f64, f64, f64) {
fn setContentsMargins(self , rsthis: & QGraphicsLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGraphicsLayout18setContentsMarginsEdddd()};
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
let arg2 = self.2 as c_double;
let arg3 = self.3 as c_double;
unsafe {C_ZN15QGraphicsLayout18setContentsMarginsEdddd(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: void QGraphicsLayout::widgetEvent(QEvent * e);
impl /*struct*/ QGraphicsLayout {
pub fn widgetEvent<RetType, T: QGraphicsLayout_widgetEvent<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.widgetEvent(self);
// return 1;
}
}
pub trait QGraphicsLayout_widgetEvent<RetType> {
fn widgetEvent(self , rsthis: & QGraphicsLayout) -> RetType;
}
// proto: void QGraphicsLayout::widgetEvent(QEvent * e);
impl<'a> /*trait*/ QGraphicsLayout_widgetEvent<()> for (&'a QEvent) {
fn widgetEvent(self , rsthis: & QGraphicsLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGraphicsLayout11widgetEventEP6QEvent()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN15QGraphicsLayout11widgetEventEP6QEvent(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: static bool QGraphicsLayout::instantInvalidatePropagation();
impl /*struct*/ QGraphicsLayout {
pub fn instantInvalidatePropagation_s<RetType, T: QGraphicsLayout_instantInvalidatePropagation_s<RetType>>( overload_args: T) -> RetType {
return overload_args.instantInvalidatePropagation_s();
// return 1;
}
}
pub trait QGraphicsLayout_instantInvalidatePropagation_s<RetType> {
fn instantInvalidatePropagation_s(self ) -> RetType;
}
// proto: static bool QGraphicsLayout::instantInvalidatePropagation();
impl<'a> /*trait*/ QGraphicsLayout_instantInvalidatePropagation_s<i8> for () {
fn instantInvalidatePropagation_s(self ) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGraphicsLayout28instantInvalidatePropagationEv()};
let mut ret = unsafe {C_ZN15QGraphicsLayout28instantInvalidatePropagationEv()};
return ret as i8; // 1
// return 1;
}
}
// proto: static void QGraphicsLayout::setInstantInvalidatePropagation(bool enable);
impl /*struct*/ QGraphicsLayout {
pub fn setInstantInvalidatePropagation_s<RetType, T: QGraphicsLayout_setInstantInvalidatePropagation_s<RetType>>( overload_args: T) -> RetType {
return overload_args.setInstantInvalidatePropagation_s();
// return 1;
}
}
pub trait QGraphicsLayout_setInstantInvalidatePropagation_s<RetType> {
fn setInstantInvalidatePropagation_s(self ) -> RetType;
}
// proto: static void QGraphicsLayout::setInstantInvalidatePropagation(bool enable);
impl<'a> /*trait*/ QGraphicsLayout_setInstantInvalidatePropagation_s<()> for (i8) {
fn setInstantInvalidatePropagation_s(self ) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGraphicsLayout31setInstantInvalidatePropagationEb()};
let arg0 = self as c_char;
unsafe {C_ZN15QGraphicsLayout31setInstantInvalidatePropagationEb(arg0)};
// return 1;
}
}
// proto: void QGraphicsLayout::~QGraphicsLayout();
impl /*struct*/ QGraphicsLayout {
pub fn free<RetType, T: QGraphicsLayout_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QGraphicsLayout_free<RetType> {
fn free(self , rsthis: & QGraphicsLayout) -> RetType;
}
// proto: void QGraphicsLayout::~QGraphicsLayout();
impl<'a> /*trait*/ QGraphicsLayout_free<()> for () {
fn free(self , rsthis: & QGraphicsLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGraphicsLayoutD2Ev()};
unsafe {C_ZN15QGraphicsLayoutD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QGraphicsLayout::activate();
impl /*struct*/ QGraphicsLayout {
pub fn activate<RetType, T: QGraphicsLayout_activate<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.activate(self);
// return 1;
}
}
pub trait QGraphicsLayout_activate<RetType> {
fn activate(self , rsthis: & QGraphicsLayout) -> RetType;
}
// proto: void QGraphicsLayout::activate();
impl<'a> /*trait*/ QGraphicsLayout_activate<()> for () {
fn activate(self , rsthis: & QGraphicsLayout) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGraphicsLayout8activateEv()};
unsafe {C_ZN15QGraphicsLayout8activateEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: int QGraphicsLayout::count();
impl /*struct*/ QGraphicsLayout {
pub fn count<RetType, T: QGraphicsLayout_count<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.count(self);
// return 1;
}
}
pub trait QGraphicsLayout_count<RetType> {
fn count(self , rsthis: & QGraphicsLayout) -> RetType;
}
// proto: int QGraphicsLayout::count();
impl<'a> /*trait*/ QGraphicsLayout_count<i32> for () {
fn count(self , rsthis: & QGraphicsLayout) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK15QGraphicsLayout5countEv()};
let mut ret = unsafe {C_ZNK15QGraphicsLayout5countEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QGraphicsLayout::QGraphicsLayout(QGraphicsLayoutItem * parent);
impl /*struct*/ QGraphicsLayout {
pub fn new<T: QGraphicsLayout_new>(value: T) -> QGraphicsLayout {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QGraphicsLayout_new {
fn new(self) -> QGraphicsLayout;
}
// proto: void QGraphicsLayout::QGraphicsLayout(QGraphicsLayoutItem * parent);
impl<'a> /*trait*/ QGraphicsLayout_new for (Option<&'a QGraphicsLayoutItem>) {
fn new(self) -> QGraphicsLayout {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN15QGraphicsLayoutC2EP19QGraphicsLayoutItem()};
let ctysz: c_int = unsafe{QGraphicsLayout_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_ZN15QGraphicsLayoutC2EP19QGraphicsLayoutItem(arg0)};
let rsthis = QGraphicsLayout{qbase: QGraphicsLayoutItem::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// <= body block end
|
#![allow(unused)]
use std::fmt::Display;
use std::fmt::Formatter;
#[derive(Debug)]
pub struct Node {
pub children: Vec<Node>,
pub node_type: NodeType
}
impl Node {
pub fn append_child(&mut self, child: Node) {
self.children.push(child);
}
pub fn add_attributes(&mut self, name: String, value: String) {
match &mut self.node_type {
NodeType::Element(_elem) => _elem.attributes.insert(name, value),
_ => None
};
}
pub fn get_attribute<K: std::string::ToString>(&self, name: K) -> Option<String> {
match &self.node_type {
NodeType::Element(_elem) => {
if let Some(_res)=_elem.attributes.get(&name.to_string()) {
Some(_res.clone())
} else {
None
}
},
_ => None
}
}
}
impl Display for Node {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match &self.node_type {
NodeType::Text(_text) => writeln!(f, "{}", _text),
NodeType::Element(_elem) => {
let mut attrs_string = String::new();
for (name, value) in _elem.attributes.iter() {
attrs_string += " ";
attrs_string = format!("{}{}=\"{}\"", attrs_string, name, value);
}
writeln!(f, "<{}{}>", _elem.tag_name, attrs_string)?;
for child in &self.children {
write!(f, "{}", child)?;
}
writeln!(f, "</{}>", _elem.tag_name)
},
NodeType::Comment(_comment) => writeln!(f, "<!--{}-->", _comment)
}
}
}
#[derive(Debug)]
pub enum NodeType {
Text(String),
Element(ElementData),
Comment(String)
}
#[derive(Debug)]
pub struct ElementData {
pub tag_name: String,
pub attributes: AttrMap
}
impl ElementData {
pub fn id(&self) -> Option<&String> {
self.attributes.get("id")
}
pub fn classes(&self) -> std::collections::HashSet<&str>{
match self.attributes.get("class") {
Some(class_list) => {class_list.split(' ').collect()},
None => std::collections::HashSet::new()
}
}
}
pub type AttrMap = std::collections::HashMap<String, String>;
pub fn text(data: String) -> Node {
Node { children: Vec::new(), node_type: NodeType::Text(data) }
}
pub fn elem(name: String, attrs: AttrMap, children: Vec<Node>) -> Node {
Node {
children: children,
node_type: NodeType::Element(ElementData {
tag_name: name,
attributes: attrs
})
}
}
pub fn comment(content: String) -> Node {
Node {
children: Vec::new(),
node_type: NodeType::Comment(content)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_dom() {
//<html><body>hello<!-- comment --></body></html>
let mut html = elem("html".to_owned(), AttrMap::new(), Vec::new());
let mut body = elem("body".to_owned(), AttrMap::new(), Vec::new());
body.append_child(text("hello".to_owned()));
body.append_child(comment(" comment ".to_owned()));
html.append_child(body);
assert_eq!(html.children.len(), 1);
assert_eq!(html.children[0].children.len(), 2);
}
}
|
/*!
The high-level plotting abstractions.
Plotters uses `ChartContext`, a thin layer on the top of `DrawingArea`, to provide
high-level chart specific drawing funcionalities, like, mesh line, coordinate label
and other common components for the data chart.
To draw a series, `ChartContext::draw_series` is used to draw a series on the chart.
In Plotters, a series is abstracted as an iterator of elements.
`ChartBuilder` is used to construct a chart. To learn more detailed information, check the
detailed description for each struct.
*/
use std::borrow::Borrow;
use std::fmt::Debug;
use std::marker::PhantomData;
use std::ops::Range;
use crate::coord::{
AsRangedCoord, CoordTranslate, MeshLine, Ranged, RangedCoord, ReverseCoordTranslate, Shift,
};
use crate::drawing::backend::{BackendCoord, DrawingBackend};
use crate::drawing::{DrawingArea, DrawingAreaErrorKind};
use crate::element::{Drawable, Path, PointCollection, Rectangle};
use crate::style::{FontDesc, Mixable, RGBColor, ShapeStyle, TextStyle, FontTransform};
/// The helper object to create a chart context, which is used for the high-level figure drawing
pub struct ChartBuilder<'a, DB: DrawingBackend> {
x_label_size: u32,
y_label_size: u32,
root_area: &'a DrawingArea<DB, Shift>,
title: Option<(String, TextStyle<'a>)>,
margin: u32,
}
impl<'a, DB: DrawingBackend> ChartBuilder<'a, DB> {
/// Create a chart builder on the given drawing area
/// - `root`: The root drawing area
/// - Returns: The chart builder object
pub fn on(root: &'a DrawingArea<DB, Shift>) -> Self {
Self {
x_label_size: 0,
y_label_size: 0,
root_area: root,
title: None,
margin: 0,
}
}
/// Set the margin size of the chart
/// - `size`: The size of the chart margin. If the chart builder is titled, we don't apply any
/// margin
pub fn margin(&mut self, size: u32) -> &mut Self {
self.margin = size;
self
}
/// Set the size of X label area
/// - `size`: The height of the x label area, if x is 0, the chart doesn't have the X label area
pub fn x_label_area_size(&mut self, size: u32) -> &mut Self {
self.x_label_size = size;
self
}
/// Set the size of the Y label area
/// - `size`: The width of the Y label area. If size is 0, the chart doesn't have Y label area
pub fn y_label_area_size(&mut self, size: u32) -> &mut Self {
self.y_label_size = size;
self
}
/// Set the caption of the chart
/// - `caption`: The caption of the chart
/// - `style`: The text style
/// - Note: If the caption is set, the margin option will be ignored
pub fn caption<S: AsRef<str>, Style: Into<TextStyle<'a>>>(
&mut self,
caption: S,
style: Style,
) -> &mut Self {
self.title = Some((caption.as_ref().to_string(), style.into()));
self
}
/// Build the chart with a 2D Cartesian coordinate system. The function will returns a chart
/// context, where data series can be rendered on.
/// - `x_spec`: The specification of X axis
/// - `y_spec`: The specification of Y axis
/// - Returns: A chart context
#[allow(clippy::type_complexity)]
pub fn build_ranged<X: AsRangedCoord, Y: AsRangedCoord>(
&mut self,
x_spec: X,
y_spec: Y,
) -> Result<
ChartContext<DB, RangedCoord<X::CoordDescType, Y::CoordDescType>>,
DrawingAreaErrorKind<DB::ErrorType>,
> {
let mut x_label_area = None;
let mut y_label_area = None;
let mut drawing_area = DrawingArea::clone(self.root_area);
if self.margin > 0 {
let s = self.margin as i32;
drawing_area = drawing_area.margin(s, s, s, s);
}
if let Some((ref title, ref style)) = self.title {
drawing_area = drawing_area.titled(title, style.clone())?;
}
if self.x_label_size > 0 {
let (_, h) = drawing_area.dim_in_pixel();
let (upper, bottom) =
drawing_area.split_vertically(h as i32 - self.x_label_size as i32);
drawing_area = upper;
x_label_area = Some(bottom);
}
if self.y_label_size > 0 {
let (left, right) = drawing_area.split_horizentally(self.y_label_size as i32);
drawing_area = right;
y_label_area = Some(left);
if let Some(xl) = x_label_area {
let (_, right) = xl.split_horizentally(self.y_label_size as i32);
x_label_area = Some(right);
}
}
let mut pixel_range = drawing_area.get_pixel_range();
pixel_range.1 = pixel_range.1.end..pixel_range.1.start;
Ok(ChartContext {
x_label_area,
y_label_area,
series_area: None,
drawing_area: drawing_area.apply_coord_spec(RangedCoord::new(
x_spec,
y_spec,
pixel_range,
)),
})
}
}
/// The context of the chart. This is the core object of Plotters.
/// Any plot/chart is abstracted as this type, and any data series can be placed to the chart
/// context.
pub struct ChartContext<DB: DrawingBackend, CT: CoordTranslate> {
x_label_area: Option<DrawingArea<DB, Shift>>,
y_label_area: Option<DrawingArea<DB, Shift>>,
series_area: Option<DrawingArea<DB, Shift>>,
drawing_area: DrawingArea<DB, CT>,
}
/// The struct that is used for tracking the configuration of a mesh of any chart
pub struct MeshStyle<'a, X: Ranged, Y: Ranged, DB>
where
DB: DrawingBackend,
{
draw_x_mesh: bool,
draw_y_mesh: bool,
draw_x_axis: bool,
draw_y_axis: bool,
x_label_offset: i32,
n_x_labels: usize,
n_y_labels: usize,
axis_desc_style: Option<TextStyle<'a>>,
x_desc: Option<String>,
y_desc: Option<String>,
line_style_1: Option<ShapeStyle<'a>>,
line_style_2: Option<ShapeStyle<'a>>,
axis_style: Option<ShapeStyle<'a>>,
label_style: Option<TextStyle<'a>>,
format_x: &'a dyn Fn(&X::ValueType) -> String,
format_y: &'a dyn Fn(&Y::ValueType) -> String,
target: Option<&'a mut ChartContext<DB, RangedCoord<X, Y>>>,
_pahtom_data: PhantomData<(X, Y)>,
}
impl<'a, X, Y, DB> MeshStyle<'a, X, Y, DB>
where
X: Ranged,
Y: Ranged,
DB: DrawingBackend,
{
/// The offset of x labels. This is used when we want to place the label in the middle of
/// the grid. This is useful if we are drawing a histogram
/// - `value`: The offset in pixel
pub fn x_label_offset(&mut self, value: i32) -> &mut Self {
self.x_label_offset = value;
self
}
/// Disable the mesh for the x axis.
pub fn disable_x_mesh(&mut self) -> &mut Self {
self.draw_x_mesh = false;
self
}
/// Disable the mesh for the y axis
pub fn disable_y_mesh(&mut self) -> &mut Self {
self.draw_y_mesh = false;
self
}
/// Disable drawing the X axis
pub fn disable_x_axis(&mut self) -> &mut Self {
self.draw_x_axis = false;
self
}
/// Disable drawing the Y axis
pub fn disable_y_axis(&mut self) -> &mut Self {
self.draw_y_axis = false;
self
}
/// Set the style definition for the axis
/// - `style`: The style for the axis
pub fn axis_style<T: Into<ShapeStyle<'a>>>(&mut self, style: T) -> &mut Self {
self.axis_style = Some(style.into());
self
}
/// Set how many labels for the X axis at most
/// - `value`: The maximum desired number of labels in the X axis
pub fn x_labels(&mut self, value: usize) -> &mut Self {
self.n_x_labels = value;
self
}
/// Set how many label for the Y axis at most
/// - `value`: The maximum desired number of labels in the Y axis
pub fn y_labels(&mut self, value: usize) -> &mut Self {
self.n_y_labels = value;
self
}
/// Set the style for the coarse grind grid
/// - `style`: This is the fcoarse grind grid style
pub fn line_style_1<T: Into<ShapeStyle<'a>>>(&mut self, style: T) -> &mut Self {
self.line_style_1 = Some(style.into());
self
}
/// Set the style for the fine grind grid
/// - `style`: The fine grind grid style
pub fn line_style_2<T: Into<ShapeStyle<'a>>>(&mut self, style: T) -> &mut Self {
self.line_style_2 = Some(style.into());
self
}
/// Set the style of the label text
/// - `style`: The text style that would be applied to the labels
pub fn label_style<T: Into<TextStyle<'a>>>(&mut self, style: T) -> &mut Self {
self.label_style = Some(style.into());
self
}
/// Set the formatter function for the X label text
/// - `fmt`: The formatter function
pub fn x_label_formatter(&mut self, fmt: &'a dyn Fn(&X::ValueType) -> String) -> &mut Self {
self.format_x = fmt;
self
}
/// Set the formatter function for the Y label text
/// - `fmt`: The formatter function
pub fn y_label_formatter(&mut self, fmt: &'a dyn Fn(&Y::ValueType) -> String) -> &mut Self {
self.format_y = fmt;
self
}
/// Set the axis description's style. If not given, use label style instead.
/// - `style`: The text style that would be applied to descriptions
pub fn axis_desc_style<T: Into<TextStyle<'a>>>(&mut self, style: T) -> &mut Self {
self.axis_desc_style = Some(style.into());
self
}
/// Set the X axis's description
/// - `desc`: The description of the X axis
pub fn x_desc<T:Into<String>>(&mut self, desc:T) -> &mut Self {
self.x_desc = Some(desc.into());
self
}
/// Set the Y axis's description
/// - `desc`: The description of the Y axis
pub fn y_desc<T:Into<String>>(&mut self, desc:T) -> &mut Self {
self.y_desc = Some(desc.into());
self
}
/// Draw the configured mesh on the target plot
pub fn draw(&mut self) -> Result<(), DrawingAreaErrorKind<DB::ErrorType>> {
let mut target = None;
std::mem::swap(&mut target, &mut self.target);
let target = target.unwrap();
let default_mesh_color_1 = RGBColor(0, 0, 0).mix(0.2);
let default_mesh_color_2 = RGBColor(0, 0, 0).mix(0.1);
let default_axis_color = RGBColor(0, 0, 0);
let default_label_font = FontDesc::new("Arial", 12.0);
let mesh_style_1 = self
.line_style_1
.clone()
.unwrap_or_else(|| (&default_mesh_color_1).into());
let mesh_style_2 = self
.line_style_2
.clone()
.unwrap_or_else(|| (&default_mesh_color_2).into());
let axis_style = self
.axis_style
.clone()
.unwrap_or_else(|| (&default_axis_color).into());
let label_style =
unsafe { std::mem::transmute::<_, Option<TextStyle>>(self.label_style.clone()) }
.unwrap_or_else(|| (&default_label_font).into());
let axis_desc_style =
unsafe { std::mem::transmute::<_, Option<TextStyle>>(self.axis_desc_style.clone()) }
.unwrap_or_else(|| label_style.clone());
target.draw_mesh(
(self.n_y_labels * 10, self.n_x_labels * 10),
&mesh_style_2,
&label_style,
|_| None,
self.draw_x_mesh,
self.draw_y_mesh,
self.x_label_offset,
false,
false,
&axis_style,
&axis_desc_style,
self.x_desc.clone(),
self.y_desc.clone(),
)?;
target.draw_mesh(
(self.n_y_labels, self.n_x_labels),
&mesh_style_1,
&label_style,
|m| match m {
MeshLine::XMesh(_, _, v) => Some((self.format_x)(v)),
MeshLine::YMesh(_, _, v) => Some((self.format_y)(v)),
},
self.draw_x_mesh,
self.draw_y_mesh,
self.x_label_offset,
self.draw_x_axis,
self.draw_y_axis,
&axis_style,
&axis_desc_style,
None,
None,
)
}
}
impl<
DB: DrawingBackend,
XT: Debug,
YT: Debug,
X: Ranged<ValueType = XT>,
Y: Ranged<ValueType = YT>,
> ChartContext<DB, RangedCoord<X, Y>>
{
/// Initialize a mesh configuration object and mesh drawing can be finalized by calling
/// the function `MeshStyle::draw`
pub fn configure_mesh(&mut self) -> MeshStyle<X, Y, DB> {
MeshStyle {
axis_style: None,
x_label_offset: 0,
draw_x_mesh: true,
draw_y_mesh: true,
draw_x_axis: true,
draw_y_axis: true,
n_x_labels: 10,
n_y_labels: 10,
line_style_1: None,
line_style_2: None,
label_style: None,
format_x: &|x| format!("{:?}", x),
format_y: &|y| format!("{:?}", y),
target: Some(self),
_pahtom_data: PhantomData,
x_desc: None,
y_desc: None,
axis_desc_style: None,
}
}
}
impl<DB: DrawingBackend, CT: ReverseCoordTranslate> ChartContext<DB, CT> {
/// Convert the chart context into an closure that can be used for coordinate translation
pub fn into_coord_trans(self) -> impl Fn(BackendCoord) -> Option<CT::From> {
let coord_spec = self.drawing_area.into_coord_spec();
move |coord| coord_spec.reverse_translate(coord)
}
}
impl<DB: DrawingBackend, X: Ranged, Y: Ranged> ChartContext<DB, RangedCoord<X, Y>> {
/// Get the range of X axis
pub fn x_range(&self) -> Range<X::ValueType> {
self.drawing_area.get_x_range()
}
/// Get range of the Y axis
pub fn y_range(&self) -> Range<Y::ValueType> {
self.drawing_area.get_y_range()
}
/// Get a reference of underlying plotting area
pub fn plotting_area(&self) -> &DrawingArea<DB, RangedCoord<X, Y>> {
&self.drawing_area
}
/*
//TODO: Redesign this
/// Defines a series label area
pub fn define_series_label_area<'a, S: Into<ShapeStyle<'a>>>(
&mut self,
pos: (u32, u32),
size: (u32, u32),
bg_style: S,
) -> Result<(), DrawingAreaErrorKind<DB::ErrorType>> {
// TODO: we should be able to draw the label
self.series_area = Some(self.drawing_area.strip_coord_spec().shrink(pos, size));
let element = Rectangle::new([(0, 0), (size.0 as i32, size.1 as i32)], bg_style.into());
self.series_area.as_ref().unwrap().draw(&element)
}
*/
/// Maps the coordinate to the backend coordinate. This is typically used
/// with an interactive chart.
pub fn backend_coord(&self, coord: &(X::ValueType, Y::ValueType)) -> BackendCoord {
self.drawing_area.map_coordinate(coord)
}
/// Draw a data series. A data series in Plotters is abstracted as an iterator of elements
pub fn draw_series<E, R, S>(&self, series: S) -> Result<(), DrawingAreaErrorKind<DB::ErrorType>>
where
for<'a> &'a E: PointCollection<'a, (X::ValueType, Y::ValueType)>,
E: Drawable<DB>,
R: Borrow<E>,
S: IntoIterator<Item = R>,
{
for element in series {
self.drawing_area.draw(element.borrow())?;
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn draw_mesh<FmtLabel>(
&mut self,
(r, c): (usize, usize),
mesh_line_style: &ShapeStyle,
label_style: &TextStyle,
mut fmt_label: FmtLabel,
x_mesh: bool,
y_mesh: bool,
x_label_offset: i32,
x_axis: bool,
y_axis: bool,
axis_style: &ShapeStyle,
axis_desc_style: &TextStyle,
x_desc: Option<String>,
y_desc: Option<String>,
) -> Result<(), DrawingAreaErrorKind<DB::ErrorType>>
where
FmtLabel: FnMut(&MeshLine<X, Y>) -> Option<String>,
{
let mut x_labels = vec![];
let mut y_labels = vec![];
self.drawing_area.draw_mesh(
|b, l| {
let draw;
match l {
MeshLine::XMesh((x, _), _, _) => {
if let Some(label_text) = fmt_label(&l) {
x_labels.push((x, label_text));
}
draw = x_mesh;
}
MeshLine::YMesh((_, y), _, _) => {
if let Some(label_text) = fmt_label(&l) {
y_labels.push((y, label_text));
}
draw = y_mesh;
}
};
if draw {
l.draw(b, mesh_line_style)
} else {
Ok(())
}
},
r,
c,
)?;
let (x0, y0) = self.drawing_area.get_base_pixel();
if let Some(ref xl) = self.x_label_area {
let (tw, th) = xl.dim_in_pixel();
if x_axis {
xl.draw(&Path::new(vec![(0, 0), (tw as i32, 0)], axis_style.clone()))?;
}
for (p, t) in x_labels {
let (w, _) = label_style.font.box_size(&t).unwrap_or((0, 0));
if p - x0 + x_label_offset > 0 && p - x0 + x_label_offset + w as i32 / 2 < tw as i32
{
if x_axis {
xl.draw(&Path::new(
vec![(p - x0, 0), (p - x0, 5)],
axis_style.clone(),
))?;
}
xl.draw_text(
&t,
label_style,
(p - x0 - w as i32 / 2 + x_label_offset, 10),
)?;
}
}
if let Some(ref text) = x_desc {
let (w, h) = label_style.font.box_size(text).unwrap_or((0, 0));
let left = (tw - w) / 2;
let top = th - h;
xl.draw_text(
&text,
axis_desc_style,
(left as i32, top as i32)
)?;
}
}
if let Some(ref yl) = self.y_label_area {
let (tw, th) = yl.dim_in_pixel();
if y_axis {
yl.draw(&Path::new(
vec![(tw as i32, 0), (tw as i32, th as i32)],
axis_style.clone(),
))?;
}
for (p, t) in y_labels {
let (w, h) = label_style.font.box_size(&t).unwrap_or((0, 0));
if p - y0 >= 0 && p - y0 - h as i32 / 2 <= th as i32 {
yl.draw_text(
&t,
label_style,
(tw as i32 - w as i32 - 10, p - y0 - h as i32 / 2),
)?;
if y_axis {
yl.draw(&Path::new(
vec![(tw as i32 - 5, p - y0), (tw as i32, p - y0)],
axis_style.clone(),
))?;
}
}
}
if let Some(ref text) = y_desc {
let (w, _) = label_style.font.box_size(text).unwrap_or((0, 0));
let top = (th - w) / 2;
let mut y_style = axis_desc_style.clone();
let y_font = axis_desc_style.font.transform(FontTransform::Rotate270);
y_style.font = &y_font;
yl.draw_text(
&text,
&y_style,
(0, top as i32)
)?;
}
}
Ok(())
}
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtWidgets/qcompleter.h
// dst-file: /src/widgets/qcompleter.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::super::core::qobject::*; // 771
use std::ops::Deref;
use super::super::core::qobjectdefs::*; // 771
use super::qabstractitemview::*; // 773
use super::super::core::qrect::*; // 771
use super::super::core::qstringlist::*; // 771
use super::super::core::qabstractitemmodel::*; // 771
use super::super::core::qstring::*; // 771
use super::qwidget::*; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QCompleter_Class_Size() -> c_int;
// proto: void QCompleter::QCompleter(QObject * parent);
fn C_ZN10QCompleterC2EP7QObject(arg0: *mut c_void) -> u64;
// proto: const QMetaObject * QCompleter::metaObject();
fn C_ZNK10QCompleter10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QAbstractItemView * QCompleter::popup();
fn C_ZNK10QCompleter5popupEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QCompleter::complete(const QRect & rect);
fn C_ZN10QCompleter8completeERK5QRect(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QCompleter::setCompletionRole(int role);
fn C_ZN10QCompleter17setCompletionRoleEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: int QCompleter::completionCount();
fn C_ZNK10QCompleter15completionCountEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QCompleter::QCompleter(const QStringList & completions, QObject * parent);
fn C_ZN10QCompleterC2ERK11QStringListP7QObject(arg0: *mut c_void, arg1: *mut c_void) -> u64;
// proto: QModelIndex QCompleter::currentIndex();
fn C_ZNK10QCompleter12currentIndexEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QString QCompleter::pathFromIndex(const QModelIndex & index);
fn C_ZNK10QCompleter13pathFromIndexERK11QModelIndex(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: void QCompleter::setMaxVisibleItems(int maxItems);
fn C_ZN10QCompleter18setMaxVisibleItemsEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: int QCompleter::completionColumn();
fn C_ZNK10QCompleter16completionColumnEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: int QCompleter::maxVisibleItems();
fn C_ZNK10QCompleter15maxVisibleItemsEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QCompleter::~QCompleter();
fn C_ZN10QCompleterD2Ev(qthis: u64 /* *mut c_void*/);
// proto: void QCompleter::setWrapAround(bool wrap);
fn C_ZN10QCompleter13setWrapAroundEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: QStringList QCompleter::splitPath(const QString & path);
fn C_ZNK10QCompleter9splitPathERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: QAbstractItemModel * QCompleter::model();
fn C_ZNK10QCompleter5modelEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QString QCompleter::currentCompletion();
fn C_ZNK10QCompleter17currentCompletionEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QCompleter::setCompletionColumn(int column);
fn C_ZN10QCompleter19setCompletionColumnEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: void QCompleter::setCompletionPrefix(const QString & prefix);
fn C_ZN10QCompleter19setCompletionPrefixERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QAbstractItemModel * QCompleter::completionModel();
fn C_ZNK10QCompleter15completionModelEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QCompleter::setCurrentRow(int row);
fn C_ZN10QCompleter13setCurrentRowEi(qthis: u64 /* *mut c_void*/, arg0: c_int) -> c_char;
// proto: int QCompleter::currentRow();
fn C_ZNK10QCompleter10currentRowEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QCompleter::setModel(QAbstractItemModel * c);
fn C_ZN10QCompleter8setModelEP18QAbstractItemModel(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: bool QCompleter::wrapAround();
fn C_ZNK10QCompleter10wrapAroundEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QCompleter::QCompleter(QAbstractItemModel * model, QObject * parent);
fn C_ZN10QCompleterC2EP18QAbstractItemModelP7QObject(arg0: *mut c_void, arg1: *mut c_void) -> u64;
// proto: void QCompleter::setPopup(QAbstractItemView * popup);
fn C_ZN10QCompleter8setPopupEP17QAbstractItemView(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QWidget * QCompleter::widget();
fn C_ZNK10QCompleter6widgetEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: int QCompleter::completionRole();
fn C_ZNK10QCompleter14completionRoleEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: QString QCompleter::completionPrefix();
fn C_ZNK10QCompleter16completionPrefixEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QCompleter::setWidget(QWidget * widget);
fn C_ZN10QCompleter9setWidgetEP7QWidget(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
fn QCompleter_SlotProxy_connect__ZN10QCompleter11highlightedERK11QModelIndex(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QCompleter_SlotProxy_connect__ZN10QCompleter9activatedERK7QString(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QCompleter_SlotProxy_connect__ZN10QCompleter9activatedERK11QModelIndex(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QCompleter_SlotProxy_connect__ZN10QCompleter11highlightedERK7QString(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QCompleter)=1
#[derive(Default)]
pub struct QCompleter {
qbase: QObject,
pub qclsinst: u64 /* *mut c_void*/,
pub _highlighted: QCompleter_highlighted_signal,
pub _activated: QCompleter_activated_signal,
}
impl /*struct*/ QCompleter {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QCompleter {
return QCompleter{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QCompleter {
type Target = QObject;
fn deref(&self) -> &QObject {
return & self.qbase;
}
}
impl AsRef<QObject> for QCompleter {
fn as_ref(& self) -> & QObject {
return & self.qbase;
}
}
// proto: void QCompleter::QCompleter(QObject * parent);
impl /*struct*/ QCompleter {
pub fn new<T: QCompleter_new>(value: T) -> QCompleter {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QCompleter_new {
fn new(self) -> QCompleter;
}
// proto: void QCompleter::QCompleter(QObject * parent);
impl<'a> /*trait*/ QCompleter_new for (Option<&'a QObject>) {
fn new(self) -> QCompleter {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QCompleterC2EP7QObject()};
let ctysz: c_int = unsafe{QCompleter_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_ZN10QCompleterC2EP7QObject(arg0)};
let rsthis = QCompleter{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: const QMetaObject * QCompleter::metaObject();
impl /*struct*/ QCompleter {
pub fn metaObject<RetType, T: QCompleter_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QCompleter_metaObject<RetType> {
fn metaObject(self , rsthis: & QCompleter) -> RetType;
}
// proto: const QMetaObject * QCompleter::metaObject();
impl<'a> /*trait*/ QCompleter_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QCompleter) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QCompleter10metaObjectEv()};
let mut ret = unsafe {C_ZNK10QCompleter10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QAbstractItemView * QCompleter::popup();
impl /*struct*/ QCompleter {
pub fn popup<RetType, T: QCompleter_popup<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.popup(self);
// return 1;
}
}
pub trait QCompleter_popup<RetType> {
fn popup(self , rsthis: & QCompleter) -> RetType;
}
// proto: QAbstractItemView * QCompleter::popup();
impl<'a> /*trait*/ QCompleter_popup<QAbstractItemView> for () {
fn popup(self , rsthis: & QCompleter) -> QAbstractItemView {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QCompleter5popupEv()};
let mut ret = unsafe {C_ZNK10QCompleter5popupEv(rsthis.qclsinst)};
let mut ret1 = QAbstractItemView::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QCompleter::complete(const QRect & rect);
impl /*struct*/ QCompleter {
pub fn complete<RetType, T: QCompleter_complete<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.complete(self);
// return 1;
}
}
pub trait QCompleter_complete<RetType> {
fn complete(self , rsthis: & QCompleter) -> RetType;
}
// proto: void QCompleter::complete(const QRect & rect);
impl<'a> /*trait*/ QCompleter_complete<()> for (Option<&'a QRect>) {
fn complete(self , rsthis: & QCompleter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QCompleter8completeERK5QRect()};
let arg0 = (if self.is_none() {QRect::new(()).qclsinst} else {self.unwrap().qclsinst}) as *mut c_void;
unsafe {C_ZN10QCompleter8completeERK5QRect(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QCompleter::setCompletionRole(int role);
impl /*struct*/ QCompleter {
pub fn setCompletionRole<RetType, T: QCompleter_setCompletionRole<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setCompletionRole(self);
// return 1;
}
}
pub trait QCompleter_setCompletionRole<RetType> {
fn setCompletionRole(self , rsthis: & QCompleter) -> RetType;
}
// proto: void QCompleter::setCompletionRole(int role);
impl<'a> /*trait*/ QCompleter_setCompletionRole<()> for (i32) {
fn setCompletionRole(self , rsthis: & QCompleter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QCompleter17setCompletionRoleEi()};
let arg0 = self as c_int;
unsafe {C_ZN10QCompleter17setCompletionRoleEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QCompleter::completionCount();
impl /*struct*/ QCompleter {
pub fn completionCount<RetType, T: QCompleter_completionCount<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.completionCount(self);
// return 1;
}
}
pub trait QCompleter_completionCount<RetType> {
fn completionCount(self , rsthis: & QCompleter) -> RetType;
}
// proto: int QCompleter::completionCount();
impl<'a> /*trait*/ QCompleter_completionCount<i32> for () {
fn completionCount(self , rsthis: & QCompleter) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QCompleter15completionCountEv()};
let mut ret = unsafe {C_ZNK10QCompleter15completionCountEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QCompleter::QCompleter(const QStringList & completions, QObject * parent);
impl<'a> /*trait*/ QCompleter_new for (&'a QStringList, Option<&'a QObject>) {
fn new(self) -> QCompleter {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QCompleterC2ERK11QStringListP7QObject()};
let ctysz: c_int = unsafe{QCompleter_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {0} else {self.1.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN10QCompleterC2ERK11QStringListP7QObject(arg0, arg1)};
let rsthis = QCompleter{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QModelIndex QCompleter::currentIndex();
impl /*struct*/ QCompleter {
pub fn currentIndex<RetType, T: QCompleter_currentIndex<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.currentIndex(self);
// return 1;
}
}
pub trait QCompleter_currentIndex<RetType> {
fn currentIndex(self , rsthis: & QCompleter) -> RetType;
}
// proto: QModelIndex QCompleter::currentIndex();
impl<'a> /*trait*/ QCompleter_currentIndex<QModelIndex> for () {
fn currentIndex(self , rsthis: & QCompleter) -> QModelIndex {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QCompleter12currentIndexEv()};
let mut ret = unsafe {C_ZNK10QCompleter12currentIndexEv(rsthis.qclsinst)};
let mut ret1 = QModelIndex::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QString QCompleter::pathFromIndex(const QModelIndex & index);
impl /*struct*/ QCompleter {
pub fn pathFromIndex<RetType, T: QCompleter_pathFromIndex<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.pathFromIndex(self);
// return 1;
}
}
pub trait QCompleter_pathFromIndex<RetType> {
fn pathFromIndex(self , rsthis: & QCompleter) -> RetType;
}
// proto: QString QCompleter::pathFromIndex(const QModelIndex & index);
impl<'a> /*trait*/ QCompleter_pathFromIndex<QString> for (&'a QModelIndex) {
fn pathFromIndex(self , rsthis: & QCompleter) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QCompleter13pathFromIndexERK11QModelIndex()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK10QCompleter13pathFromIndexERK11QModelIndex(rsthis.qclsinst, arg0)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QCompleter::setMaxVisibleItems(int maxItems);
impl /*struct*/ QCompleter {
pub fn setMaxVisibleItems<RetType, T: QCompleter_setMaxVisibleItems<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setMaxVisibleItems(self);
// return 1;
}
}
pub trait QCompleter_setMaxVisibleItems<RetType> {
fn setMaxVisibleItems(self , rsthis: & QCompleter) -> RetType;
}
// proto: void QCompleter::setMaxVisibleItems(int maxItems);
impl<'a> /*trait*/ QCompleter_setMaxVisibleItems<()> for (i32) {
fn setMaxVisibleItems(self , rsthis: & QCompleter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QCompleter18setMaxVisibleItemsEi()};
let arg0 = self as c_int;
unsafe {C_ZN10QCompleter18setMaxVisibleItemsEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: int QCompleter::completionColumn();
impl /*struct*/ QCompleter {
pub fn completionColumn<RetType, T: QCompleter_completionColumn<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.completionColumn(self);
// return 1;
}
}
pub trait QCompleter_completionColumn<RetType> {
fn completionColumn(self , rsthis: & QCompleter) -> RetType;
}
// proto: int QCompleter::completionColumn();
impl<'a> /*trait*/ QCompleter_completionColumn<i32> for () {
fn completionColumn(self , rsthis: & QCompleter) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QCompleter16completionColumnEv()};
let mut ret = unsafe {C_ZNK10QCompleter16completionColumnEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: int QCompleter::maxVisibleItems();
impl /*struct*/ QCompleter {
pub fn maxVisibleItems<RetType, T: QCompleter_maxVisibleItems<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.maxVisibleItems(self);
// return 1;
}
}
pub trait QCompleter_maxVisibleItems<RetType> {
fn maxVisibleItems(self , rsthis: & QCompleter) -> RetType;
}
// proto: int QCompleter::maxVisibleItems();
impl<'a> /*trait*/ QCompleter_maxVisibleItems<i32> for () {
fn maxVisibleItems(self , rsthis: & QCompleter) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QCompleter15maxVisibleItemsEv()};
let mut ret = unsafe {C_ZNK10QCompleter15maxVisibleItemsEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QCompleter::~QCompleter();
impl /*struct*/ QCompleter {
pub fn free<RetType, T: QCompleter_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QCompleter_free<RetType> {
fn free(self , rsthis: & QCompleter) -> RetType;
}
// proto: void QCompleter::~QCompleter();
impl<'a> /*trait*/ QCompleter_free<()> for () {
fn free(self , rsthis: & QCompleter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QCompleterD2Ev()};
unsafe {C_ZN10QCompleterD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QCompleter::setWrapAround(bool wrap);
impl /*struct*/ QCompleter {
pub fn setWrapAround<RetType, T: QCompleter_setWrapAround<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setWrapAround(self);
// return 1;
}
}
pub trait QCompleter_setWrapAround<RetType> {
fn setWrapAround(self , rsthis: & QCompleter) -> RetType;
}
// proto: void QCompleter::setWrapAround(bool wrap);
impl<'a> /*trait*/ QCompleter_setWrapAround<()> for (i8) {
fn setWrapAround(self , rsthis: & QCompleter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QCompleter13setWrapAroundEb()};
let arg0 = self as c_char;
unsafe {C_ZN10QCompleter13setWrapAroundEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QStringList QCompleter::splitPath(const QString & path);
impl /*struct*/ QCompleter {
pub fn splitPath<RetType, T: QCompleter_splitPath<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.splitPath(self);
// return 1;
}
}
pub trait QCompleter_splitPath<RetType> {
fn splitPath(self , rsthis: & QCompleter) -> RetType;
}
// proto: QStringList QCompleter::splitPath(const QString & path);
impl<'a> /*trait*/ QCompleter_splitPath<QStringList> for (&'a QString) {
fn splitPath(self , rsthis: & QCompleter) -> QStringList {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QCompleter9splitPathERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK10QCompleter9splitPathERK7QString(rsthis.qclsinst, arg0)};
let mut ret1 = QStringList::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QAbstractItemModel * QCompleter::model();
impl /*struct*/ QCompleter {
pub fn model<RetType, T: QCompleter_model<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.model(self);
// return 1;
}
}
pub trait QCompleter_model<RetType> {
fn model(self , rsthis: & QCompleter) -> RetType;
}
// proto: QAbstractItemModel * QCompleter::model();
impl<'a> /*trait*/ QCompleter_model<QAbstractItemModel> for () {
fn model(self , rsthis: & QCompleter) -> QAbstractItemModel {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QCompleter5modelEv()};
let mut ret = unsafe {C_ZNK10QCompleter5modelEv(rsthis.qclsinst)};
let mut ret1 = QAbstractItemModel::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QString QCompleter::currentCompletion();
impl /*struct*/ QCompleter {
pub fn currentCompletion<RetType, T: QCompleter_currentCompletion<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.currentCompletion(self);
// return 1;
}
}
pub trait QCompleter_currentCompletion<RetType> {
fn currentCompletion(self , rsthis: & QCompleter) -> RetType;
}
// proto: QString QCompleter::currentCompletion();
impl<'a> /*trait*/ QCompleter_currentCompletion<QString> for () {
fn currentCompletion(self , rsthis: & QCompleter) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QCompleter17currentCompletionEv()};
let mut ret = unsafe {C_ZNK10QCompleter17currentCompletionEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QCompleter::setCompletionColumn(int column);
impl /*struct*/ QCompleter {
pub fn setCompletionColumn<RetType, T: QCompleter_setCompletionColumn<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setCompletionColumn(self);
// return 1;
}
}
pub trait QCompleter_setCompletionColumn<RetType> {
fn setCompletionColumn(self , rsthis: & QCompleter) -> RetType;
}
// proto: void QCompleter::setCompletionColumn(int column);
impl<'a> /*trait*/ QCompleter_setCompletionColumn<()> for (i32) {
fn setCompletionColumn(self , rsthis: & QCompleter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QCompleter19setCompletionColumnEi()};
let arg0 = self as c_int;
unsafe {C_ZN10QCompleter19setCompletionColumnEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QCompleter::setCompletionPrefix(const QString & prefix);
impl /*struct*/ QCompleter {
pub fn setCompletionPrefix<RetType, T: QCompleter_setCompletionPrefix<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setCompletionPrefix(self);
// return 1;
}
}
pub trait QCompleter_setCompletionPrefix<RetType> {
fn setCompletionPrefix(self , rsthis: & QCompleter) -> RetType;
}
// proto: void QCompleter::setCompletionPrefix(const QString & prefix);
impl<'a> /*trait*/ QCompleter_setCompletionPrefix<()> for (&'a QString) {
fn setCompletionPrefix(self , rsthis: & QCompleter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QCompleter19setCompletionPrefixERK7QString()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN10QCompleter19setCompletionPrefixERK7QString(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QAbstractItemModel * QCompleter::completionModel();
impl /*struct*/ QCompleter {
pub fn completionModel<RetType, T: QCompleter_completionModel<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.completionModel(self);
// return 1;
}
}
pub trait QCompleter_completionModel<RetType> {
fn completionModel(self , rsthis: & QCompleter) -> RetType;
}
// proto: QAbstractItemModel * QCompleter::completionModel();
impl<'a> /*trait*/ QCompleter_completionModel<QAbstractItemModel> for () {
fn completionModel(self , rsthis: & QCompleter) -> QAbstractItemModel {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QCompleter15completionModelEv()};
let mut ret = unsafe {C_ZNK10QCompleter15completionModelEv(rsthis.qclsinst)};
let mut ret1 = QAbstractItemModel::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QCompleter::setCurrentRow(int row);
impl /*struct*/ QCompleter {
pub fn setCurrentRow<RetType, T: QCompleter_setCurrentRow<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setCurrentRow(self);
// return 1;
}
}
pub trait QCompleter_setCurrentRow<RetType> {
fn setCurrentRow(self , rsthis: & QCompleter) -> RetType;
}
// proto: bool QCompleter::setCurrentRow(int row);
impl<'a> /*trait*/ QCompleter_setCurrentRow<i8> for (i32) {
fn setCurrentRow(self , rsthis: & QCompleter) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QCompleter13setCurrentRowEi()};
let arg0 = self as c_int;
let mut ret = unsafe {C_ZN10QCompleter13setCurrentRowEi(rsthis.qclsinst, arg0)};
return ret as i8; // 1
// return 1;
}
}
// proto: int QCompleter::currentRow();
impl /*struct*/ QCompleter {
pub fn currentRow<RetType, T: QCompleter_currentRow<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.currentRow(self);
// return 1;
}
}
pub trait QCompleter_currentRow<RetType> {
fn currentRow(self , rsthis: & QCompleter) -> RetType;
}
// proto: int QCompleter::currentRow();
impl<'a> /*trait*/ QCompleter_currentRow<i32> for () {
fn currentRow(self , rsthis: & QCompleter) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QCompleter10currentRowEv()};
let mut ret = unsafe {C_ZNK10QCompleter10currentRowEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QCompleter::setModel(QAbstractItemModel * c);
impl /*struct*/ QCompleter {
pub fn setModel<RetType, T: QCompleter_setModel<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setModel(self);
// return 1;
}
}
pub trait QCompleter_setModel<RetType> {
fn setModel(self , rsthis: & QCompleter) -> RetType;
}
// proto: void QCompleter::setModel(QAbstractItemModel * c);
impl<'a> /*trait*/ QCompleter_setModel<()> for (&'a QAbstractItemModel) {
fn setModel(self , rsthis: & QCompleter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QCompleter8setModelEP18QAbstractItemModel()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN10QCompleter8setModelEP18QAbstractItemModel(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: bool QCompleter::wrapAround();
impl /*struct*/ QCompleter {
pub fn wrapAround<RetType, T: QCompleter_wrapAround<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.wrapAround(self);
// return 1;
}
}
pub trait QCompleter_wrapAround<RetType> {
fn wrapAround(self , rsthis: & QCompleter) -> RetType;
}
// proto: bool QCompleter::wrapAround();
impl<'a> /*trait*/ QCompleter_wrapAround<i8> for () {
fn wrapAround(self , rsthis: & QCompleter) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QCompleter10wrapAroundEv()};
let mut ret = unsafe {C_ZNK10QCompleter10wrapAroundEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QCompleter::QCompleter(QAbstractItemModel * model, QObject * parent);
impl<'a> /*trait*/ QCompleter_new for (&'a QAbstractItemModel, Option<&'a QObject>) {
fn new(self) -> QCompleter {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QCompleterC2EP18QAbstractItemModelP7QObject()};
let ctysz: c_int = unsafe{QCompleter_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {0} else {self.1.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN10QCompleterC2EP18QAbstractItemModelP7QObject(arg0, arg1)};
let rsthis = QCompleter{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QCompleter::setPopup(QAbstractItemView * popup);
impl /*struct*/ QCompleter {
pub fn setPopup<RetType, T: QCompleter_setPopup<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setPopup(self);
// return 1;
}
}
pub trait QCompleter_setPopup<RetType> {
fn setPopup(self , rsthis: & QCompleter) -> RetType;
}
// proto: void QCompleter::setPopup(QAbstractItemView * popup);
impl<'a> /*trait*/ QCompleter_setPopup<()> for (&'a QAbstractItemView) {
fn setPopup(self , rsthis: & QCompleter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QCompleter8setPopupEP17QAbstractItemView()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN10QCompleter8setPopupEP17QAbstractItemView(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QWidget * QCompleter::widget();
impl /*struct*/ QCompleter {
pub fn widget<RetType, T: QCompleter_widget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.widget(self);
// return 1;
}
}
pub trait QCompleter_widget<RetType> {
fn widget(self , rsthis: & QCompleter) -> RetType;
}
// proto: QWidget * QCompleter::widget();
impl<'a> /*trait*/ QCompleter_widget<QWidget> for () {
fn widget(self , rsthis: & QCompleter) -> QWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QCompleter6widgetEv()};
let mut ret = unsafe {C_ZNK10QCompleter6widgetEv(rsthis.qclsinst)};
let mut ret1 = QWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QCompleter::completionRole();
impl /*struct*/ QCompleter {
pub fn completionRole<RetType, T: QCompleter_completionRole<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.completionRole(self);
// return 1;
}
}
pub trait QCompleter_completionRole<RetType> {
fn completionRole(self , rsthis: & QCompleter) -> RetType;
}
// proto: int QCompleter::completionRole();
impl<'a> /*trait*/ QCompleter_completionRole<i32> for () {
fn completionRole(self , rsthis: & QCompleter) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QCompleter14completionRoleEv()};
let mut ret = unsafe {C_ZNK10QCompleter14completionRoleEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: QString QCompleter::completionPrefix();
impl /*struct*/ QCompleter {
pub fn completionPrefix<RetType, T: QCompleter_completionPrefix<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.completionPrefix(self);
// return 1;
}
}
pub trait QCompleter_completionPrefix<RetType> {
fn completionPrefix(self , rsthis: & QCompleter) -> RetType;
}
// proto: QString QCompleter::completionPrefix();
impl<'a> /*trait*/ QCompleter_completionPrefix<QString> for () {
fn completionPrefix(self , rsthis: & QCompleter) -> QString {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QCompleter16completionPrefixEv()};
let mut ret = unsafe {C_ZNK10QCompleter16completionPrefixEv(rsthis.qclsinst)};
let mut ret1 = QString::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QCompleter::setWidget(QWidget * widget);
impl /*struct*/ QCompleter {
pub fn setWidget<RetType, T: QCompleter_setWidget<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setWidget(self);
// return 1;
}
}
pub trait QCompleter_setWidget<RetType> {
fn setWidget(self , rsthis: & QCompleter) -> RetType;
}
// proto: void QCompleter::setWidget(QWidget * widget);
impl<'a> /*trait*/ QCompleter_setWidget<()> for (&'a QWidget) {
fn setWidget(self , rsthis: & QCompleter) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QCompleter9setWidgetEP7QWidget()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN10QCompleter9setWidgetEP7QWidget(rsthis.qclsinst, arg0)};
// return 1;
}
}
#[derive(Default)] // for QCompleter_highlighted
pub struct QCompleter_highlighted_signal{poi:u64}
impl /* struct */ QCompleter {
pub fn highlighted(&self) -> QCompleter_highlighted_signal {
return QCompleter_highlighted_signal{poi:self.qclsinst};
}
}
impl /* struct */ QCompleter_highlighted_signal {
pub fn connect<T: QCompleter_highlighted_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QCompleter_highlighted_signal_connect {
fn connect(self, sigthis: QCompleter_highlighted_signal);
}
#[derive(Default)] // for QCompleter_activated
pub struct QCompleter_activated_signal{poi:u64}
impl /* struct */ QCompleter {
pub fn activated(&self) -> QCompleter_activated_signal {
return QCompleter_activated_signal{poi:self.qclsinst};
}
}
impl /* struct */ QCompleter_activated_signal {
pub fn connect<T: QCompleter_activated_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QCompleter_activated_signal_connect {
fn connect(self, sigthis: QCompleter_activated_signal);
}
// highlighted(const class QModelIndex &)
extern fn QCompleter_highlighted_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 QCompleter_highlighted_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 */ QCompleter_highlighted_signal_connect for fn(QModelIndex) {
fn connect(self, sigthis: QCompleter_highlighted_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 = QCompleter_highlighted_signal_connect_cb_0 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QCompleter_SlotProxy_connect__ZN10QCompleter11highlightedERK11QModelIndex(arg0, arg1, arg2)};
}
}
impl /* trait */ QCompleter_highlighted_signal_connect for Box<Fn(QModelIndex)> {
fn connect(self, sigthis: QCompleter_highlighted_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 = QCompleter_highlighted_signal_connect_cb_box_0 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QCompleter_SlotProxy_connect__ZN10QCompleter11highlightedERK11QModelIndex(arg0, arg1, arg2)};
}
}
// activated(const class QString &)
extern fn QCompleter_activated_signal_connect_cb_1(rsfptr:fn(QString), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QString::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QCompleter_activated_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn(QString)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QString::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QCompleter_activated_signal_connect for fn(QString) {
fn connect(self, sigthis: QCompleter_activated_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 = QCompleter_activated_signal_connect_cb_1 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QCompleter_SlotProxy_connect__ZN10QCompleter9activatedERK7QString(arg0, arg1, arg2)};
}
}
impl /* trait */ QCompleter_activated_signal_connect for Box<Fn(QString)> {
fn connect(self, sigthis: QCompleter_activated_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 = QCompleter_activated_signal_connect_cb_box_1 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QCompleter_SlotProxy_connect__ZN10QCompleter9activatedERK7QString(arg0, arg1, arg2)};
}
}
// activated(const class QModelIndex &)
extern fn QCompleter_activated_signal_connect_cb_2(rsfptr:fn(QModelIndex), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QModelIndex::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QCompleter_activated_signal_connect_cb_box_2(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 */ QCompleter_activated_signal_connect for fn(QModelIndex) {
fn connect(self, sigthis: QCompleter_activated_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 = QCompleter_activated_signal_connect_cb_2 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QCompleter_SlotProxy_connect__ZN10QCompleter9activatedERK11QModelIndex(arg0, arg1, arg2)};
}
}
impl /* trait */ QCompleter_activated_signal_connect for Box<Fn(QModelIndex)> {
fn connect(self, sigthis: QCompleter_activated_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 = QCompleter_activated_signal_connect_cb_box_2 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QCompleter_SlotProxy_connect__ZN10QCompleter9activatedERK11QModelIndex(arg0, arg1, arg2)};
}
}
// highlighted(const class QString &)
extern fn QCompleter_highlighted_signal_connect_cb_3(rsfptr:fn(QString), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QString::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QCompleter_highlighted_signal_connect_cb_box_3(rsfptr_raw:*mut Box<Fn(QString)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QString::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QCompleter_highlighted_signal_connect for fn(QString) {
fn connect(self, sigthis: QCompleter_highlighted_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 = QCompleter_highlighted_signal_connect_cb_3 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QCompleter_SlotProxy_connect__ZN10QCompleter11highlightedERK7QString(arg0, arg1, arg2)};
}
}
impl /* trait */ QCompleter_highlighted_signal_connect for Box<Fn(QString)> {
fn connect(self, sigthis: QCompleter_highlighted_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 = QCompleter_highlighted_signal_connect_cb_box_3 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QCompleter_SlotProxy_connect__ZN10QCompleter11highlightedERK7QString(arg0, arg1, arg2)};
}
}
// <= body block end
|
use ndarray_linalg::*;
use super::da::{EnsembleAnalyzer, Setting};
use super::observation::*;
use super::stat::*;
use super::types::*;
/// Ensemble Kalman Filter with perturbed observation implementation
#[derive(Clone, Debug)]
pub struct EnKF {
obs: LinearNormal,
}
impl EnKF {
pub fn new(setting: &Setting) -> Self {
EnKF { obs: LinearNormal::isotropic(3, setting.r) }
}
}
impl EnsembleAnalyzer for EnKF {
fn analysis(&self, xs: Ensemble, y: &V) -> Ensemble {
let ys = xs.iter().map(|x| self.obs.noisy_eval(x)).collect();
let v = covar(&ys, &ys);
let u = covar(&xs, &ys);
let k = u.dot(&v.inv().unwrap());
xs.into_iter()
.map(|x| {
let err = y - &self.obs.noisy_eval(&x);
x + k.dot(&err)
})
.collect()
}
}
|
//让我们一起来玩扫雷游戏!
//
// 给定一个代表游戏板的二维字符矩阵。 'M' 代表一个未挖出的地雷,'E' 代表一个未挖出的空方块,'B' 代表没有相邻(上,下,左,右,和所有4个对角线)
//地雷的已挖出的空白方块,数字('1' 到 '8')表示有多少地雷与这块已挖出的方块相邻,'X' 则表示一个已挖出的地雷。
//
// 现在给出在所有未挖出的方块中('M'或者'E')的下一个点击位置(行和列索引),根据以下规则,返回相应位置被点击后对应的面板:
//
//
// 如果一个地雷('M')被挖出,游戏就结束了- 把它改为 'X'。
// 如果一个没有相邻地雷的空方块('E')被挖出,修改它为('B'),并且所有和其相邻的方块都应该被递归地揭露。
// 如果一个至少与一个地雷相邻的空方块('E')被挖出,修改它为数字('1'到'8'),表示相邻地雷的数量。
// 如果在此次点击中,若无更多方块可被揭露,则返回面板。
//
//
//
//
// 示例 1:
//
// 输入:
//
//[['E', 'E', 'E', 'E', 'E'],
// ['E', 'E', 'M', 'E', 'E'],
// ['E', 'E', 'E', 'E', 'E'],
// ['E', 'E', 'E', 'E', 'E']]
//
//Click : [3,0]
//
//输出:
//
//[['B', '1', 'E', '1', 'B'],
// ['B', '1', 'M', '1', 'B'],
// ['B', '1', '1', '1', 'B'],
// ['B', 'B', 'B', 'B', 'B']]
//
//解释:
//
//
//
// 示例 2:
//
// 输入:
//
//[['B', '1', 'E', '1', 'B'],
// ['B', '1', 'M', '1', 'B'],
// ['B', '1', '1', '1', 'B'],
// ['B', 'B', 'B', 'B', 'B']]
//
//Click : [1,2]
//
//输出:
//
//[['B', '1', 'E', '1', 'B'],
// ['B', '1', 'X', '1', 'B'],
// ['B', '1', '1', '1', 'B'],
// ['B', 'B', 'B', 'B', 'B']]
//
//解释:
//
//
//
//
//
// 注意:
//
//
// 输入矩阵的宽和高的范围为 [1,50]。
// 点击的位置只能是未被挖出的方块 ('M' 或者 'E'),这也意味着面板至少包含一个可点击的方块。
// 输入面板不会是游戏结束的状态(即有地雷已被挖出)。
// 简单起见,未提及的规则在这个问题中可被忽略。例如,当游戏结束时你不需要挖出所有地雷,考虑所有你可能赢得游戏或标记方块的情况。
// Related Topics 深度优先搜索 广度优先搜索
//leetcode submit region begin(Prohibit modification and deletion)
impl Solution {
pub fn update_board(mut board: Vec<Vec<char>>, click: Vec<i32>) -> Vec<Vec<char>> {
let x: usize = click[0] as usize;
let y: usize = click[1] as usize;
let s = board[x][y];
match s {
'M' => {
board[x][y] = 'X';
return board;
}
'E' => {
let x = x as i32;
let y = y as i32;
let mut count = 0;
for i in -1..=1 {
for j in -1..=1 {
if (x + i) < 0 || x + i >= board.len() as i32 {
continue;
}
if (y + j) < 0 || y + j >= board[0].len() as i32 {
continue;
}
if board[(x + i) as usize][(y + j) as usize] == 'M' {
count += 1;
}
}
}
if count > 0 {
board[x as usize][y as usize] = char::from(count + '0' as u8);
return board;
} else {
board[x as usize][y as usize] = 'B';
for i in -1..=1 {
for j in -1..=1 {
if (x + i) < 0 || x + i >= board.len() as i32 {
continue;
}
if (y + j) < 0 || y + j >= board[0].len() as i32 {
continue;
}
board = Self::update_board(board, vec![x + i, y + j]);
}
}
return board;
}
}
'B' => {}
_ if s.is_numeric() => {}
_ => {
unreachable!();
}
}
return board;
}
}
//leetcode submit region end(Prohibit modification and deletion)
struct Solution {}
fn main() {
let v = vec![
vec!['B', '1', 'E', '1', 'B'],
vec!['B', '1', 'M', '1', 'B'],
vec!['B', '1', '1', '1', 'B'],
vec!['B', 'B', 'B', 'B', 'B'],
];
check(v.clone(), vec![1, 2]);
check(v, vec![0, 2]);
let b = vec![
vec!['E', 'E', 'E', 'E', 'E'],
vec!['E', 'E', 'M', 'E', 'E'],
vec!['E', 'E', 'E', 'E', 'E'],
vec!['E', 'E', 'E', 'E', 'E'],
];
check(b.clone(), vec![3, 0]);
check(b.clone(), vec![0, 0]);
}
fn check(v: Vec<Vec<char>>, click: Vec<i32>) -> () {
let s = Solution::update_board(v, click);
s.iter().for_each(|line| {
println!("{:?}", line);
});
println!();
}
|
use std::collections::HashMap;
use crate::error::LuxError;
use crate::literal::{Float, Literal};
use crate::token::Token;
use crate::token_type::Types;
pub struct Scanner {
source: String,
tokens: Vec<Token>,
start: usize,
current: usize,
line: usize,
keywords: HashMap<String, Types>,
}
impl Scanner {
pub fn new(source: String) -> Scanner {
let mut scanner = Scanner {
source,
tokens: Vec::new(),
start: 0,
current: 0,
line: 1,
keywords: HashMap::new(),
};
scanner.keywords.insert("and".to_string(), Types::AND);
scanner.keywords.insert("class".to_string(), Types::CLASS);
scanner.keywords.insert("else".to_string(), Types::ELSE);
scanner.keywords.insert("false".to_string(), Types::FALSE);
scanner.keywords.insert("for".to_string(), Types::FOR);
scanner.keywords.insert("fun".to_string(), Types::FUN);
scanner.keywords.insert("if".to_string(), Types::IF);
scanner.keywords.insert("nil".to_string(), Types::NIL);
scanner.keywords.insert("or".to_string(), Types::OR);
scanner.keywords.insert("print".to_string(), Types::PRINT);
scanner.keywords.insert("return".to_string(), Types::RETURN);
scanner.keywords.insert("super".to_string(), Types::SUPER);
scanner.keywords.insert("this".to_string(), Types::THIS);
scanner.keywords.insert("true".to_string(), Types::TRUE);
scanner.keywords.insert("var".to_string(), Types::VAR);
scanner.keywords.insert("while".to_string(), Types::WHILE);
scanner
}
pub fn scan_tokens(&mut self) -> &Vec<Token> {
while !self.is_at_end() {
// We are at the beginning of the next lexeme.
self.start = self.current;
self.scan_token().unwrap();
}
let token = Token::new(Types::EOF, "".to_string(), Literal::Nil, self.line);
self.tokens.push(token);
&self.tokens
}
fn is_at_end(&self) -> bool {
self.current >= self.source.len()
}
pub fn scan_token(&mut self) -> Result<(), LuxError> {
let c = self.advance();
match c {
'(' => {
self.add_token(Types::LEFT_PAREN);
Ok(())
}
')' => {
self.add_token(Types::RIGHT_PAREN);
Ok(())
}
'{' => {
self.add_token(Types::LEFT_BRACE);
Ok(())
}
'}' => {
self.add_token(Types::RIGHT_BRACE);
Ok(())
}
',' => {
self.add_token(Types::COMMA);
Ok(())
}
'.' => {
self.add_token(Types::DOT);
Ok(())
}
'-' => {
self.add_token(Types::MINUS);
Ok(())
}
'+' => {
self.add_token(Types::PLUS);
Ok(())
}
';' => {
self.add_token(Types::SEMICOLON);
Ok(())
}
'*' => {
self.add_token(Types::STAR);
Ok(())
}
'!' => {
let token_to_add = if self.matches_char('=') {
Types::BANG_EQUAL
} else {
Types::BANG
};
self.add_token(token_to_add);
Ok(())
}
'=' => {
let token_to_add = if self.matches_char('=') {
Types::EQUAL_EQUAL
} else {
Types::EQUAL
};
self.add_token(token_to_add);
Ok(())
}
'<' => {
let token_to_add = if self.matches_char('=') {
Types::LESS_EQUAL
} else {
Types::LESS
};
self.add_token(token_to_add);
Ok(())
}
'>' => {
let token_to_add = if self.matches_char('=') {
Types::GREATER_EQUAL
} else {
Types::GREATER
};
self.add_token(token_to_add);
Ok(())
}
'/' => {
if self.matches_char('/') {
while self.peek() != '\n' && !self.is_at_end() {
self.advance();
}
} else {
self.add_token(Types::SLASH)
};
Ok(())
}
' ' => Ok(()),
'\r' => Ok(()),
'\t' => Ok(()),
'\n' => {
self.line += 1;
Ok(())
}
'"' => {
self.string().unwrap();
Ok(())
}
ident => {
if Scanner::is_digit(ident) {
self.number();
Ok(())
} else if Scanner::is_alpha(ident) {
self.identifier();
Ok(())
} else {
Err(LuxError {
line: self.line,
location: "".to_string(),
message: "Unexpected character".to_string(),
})
}
}
}
}
pub fn advance(&mut self) -> char {
let next_char = &self
.source
.chars()
.nth(self.current)
.expect("Failed to read char from advance method");
self.current += 1;
next_char.to_owned()
}
pub fn add_token(&mut self, token_type: Types) {
self.add_token_literal(token_type, Literal::Nil)
}
fn add_token_literal(&mut self, token_type: Types, literal: Literal) {
let text = &self.source[self.start..self.current];
self.tokens
.push(Token::new(token_type, text.to_string(), literal, self.line))
}
fn matches_char(&mut self, expected: char) -> bool {
if self.is_at_end() || self.source.chars().nth(self.current).unwrap() != expected {
false
} else {
self.current += 1;
true
}
}
fn peek(&mut self) -> char {
if self.is_at_end() {
'\0'
} else {
self.source.chars().nth(self.current).unwrap()
}
}
fn string(&mut self) -> Result<(), LuxError> {
while self.peek() != '"' && !self.is_at_end() {
if self.peek() == '\n' {
self.line += 1;
}
self.advance();
}
if self.is_at_end() {
return Err(LuxError {
line: self.line,
location: "".to_string(),
message: "Unterminated string".to_string(),
});
}
self.advance();
let value = (&self.source[self.start + 1..self.current - 1]).to_string();
self.add_token_literal(Types::STRING, Literal::String(value));
Ok(())
}
fn number(&mut self) {
while Scanner::is_digit(self.peek()) {
self.advance();
}
if self.peek() == '.' && Scanner::is_digit(self.peek_next()) {
self.advance();
while Scanner::is_digit(self.peek()) {
self.advance();
}
}
let num = (&self.source[self.start..self.current]).parse().unwrap();
self.add_token_literal(Types::NUMBER, Literal::Number(Float(num)))
}
fn peek_next(&mut self) -> char {
if self.current + 1 >= self.source.len() {
'\0'
} else {
self.source.chars().nth(self.current + 1).unwrap()
}
}
fn identifier(&mut self) {
while Scanner::is_alphanumeric(self.peek()) {
self.advance();
}
let text = &self.source[self.start..self.current];
let token_type = self
.keywords
.get(text)
.unwrap_or(&Types::IDENTIFIER)
.to_owned();
self.add_token(token_type);
}
fn is_alpha(char: char) -> bool {
('a'..='z').contains(&char) || ('A'..='Z').contains(&char) || char == '_'
}
fn is_digit(char: char) -> bool {
('0'..='9').contains(&char)
}
fn is_alphanumeric(char: char) -> bool {
Scanner::is_alpha(char) || Scanner::is_digit(char)
}
}
|
#![feature(inclusive_range_syntax)]
pub fn sum_of_squares(n: u64) -> u64 {
(0...n).map(|n| n * n).sum()
}
pub fn square_of_sum(n: u64) -> u64 {
let x: u64 = (0...n).sum();
x * x
}
pub fn difference(n: u64) -> u64 {
square_of_sum(n) - sum_of_squares(n)
}
|
use clap::{App, load_yaml};
use image::{Luma, RgbImage, Rgb};
fn is_bright(noise_color: &Luma<u8>, picture_color: &Luma<u8>) -> bool {
let noise_luma = noise_color.0;
let picture_luma = picture_color.0;
if picture_luma[0] > noise_luma[0] {
true
} else {
false
}
}
fn wrap(m: u32, n: u32) -> u32 {
return n % m;
}
fn main() {
let yaml = load_yaml!("cli.yaml");
let matches = App::from(yaml).get_matches();
let input_file = matches.value_of("INPUT").unwrap();
let output_file = matches.value_of("OUTPUT").unwrap();
let old_img = image::open(input_file).unwrap();
let mut old_img = old_img.grayscale();
let old_img = old_img.as_mut_luma8().unwrap();
let (old_width, old_height) = old_img.dimensions();
let noise_img = image::open("img/noise.png").unwrap();
let mut noise_img = noise_img.grayscale();
let noise_img = noise_img.as_mut_luma8().unwrap();
let (noise_width, noise_height) = noise_img.dimensions();
let mut new_img = RgbImage::new(old_width, old_height);
for x in 0..old_width {
for y in 0..old_height {
let wrap_x = wrap(noise_width, x);
let wrap_y = wrap(noise_height, y);
let noise_pixel = noise_img.get_pixel_mut(wrap_x, wrap_y);
let old_pixel = old_img.get_pixel_mut(x, y);
if is_bright(noise_pixel, old_pixel) {
new_img.put_pixel(x, y, Rgb([255, 255, 255]));
} else {
new_img.put_pixel(x, y, Rgb([0, 0, 0]));
}
}
}
new_img.save(&output_file).unwrap();
println!("File saved to {}", &output_file);
}
|
use std::fmt::Display;
use serde::de::Error as DeError;
use serde::ser::Error as SerError;
error_chain! {
types {
Error,
ErrorKind,
ResultExt,
Result;
}
foreign_links {
Io(::std::io::Error);
FromUtf8Error(::std::string::FromUtf8Error);
ParseIntError(::std::num::ParseIntError);
ParseFloatError(::std::num::ParseFloatError);
ParseBoolError(::std::str::ParseBoolError);
Syntax(::xml::reader::Error);
}
errors {
UnexpectedToken(token: String, found: String) {
description("unexpected token")
display("Expected token {}, found {}", token, found)
}
Custom(field: String) {
description("other error")
display("custom: '{}'", field)
}
UnsupportedOperation(operation: String) {
description("unsupported operation")
display("unsupported operation: '{}'", operation)
}
NonPrimitiveKey {
description("Map key has non-primitive value")
display("Map key has non-primitive value")
}
}
}
macro_rules! expect {
($actual: expr, $($expected: pat)|+ => $if_ok: expr) => {
match $actual {
$($expected)|+ => $if_ok,
actual => Err($crate::ErrorKind::UnexpectedToken(
stringify!($($expected)|+).to_string(), format!("{:?}",actual)
).into()) as Result<_>
}
}
}
#[cfg(debug_assertions)]
macro_rules! debug_expect {
($actual: expr, $($expected: pat)|+ => $if_ok: expr) => {
match $actual {
$($expected)|+ => $if_ok,
actual => panic!(
"Internal error: Expected token {}, found {:?}",
stringify!($($expected)|+),
actual
)
}
}
}
#[cfg(not(debug_assertions))]
macro_rules! debug_expect {
($actual: expr, $($expected: pat)|+ => $if_ok: expr) => {
match $actual {
$($expected)|+ => $if_ok,
_ => unreachable!()
}
}
}
impl DeError for Error {
fn custom<T: Display>(msg: T) -> Self {
ErrorKind::Custom(msg.to_string()).into()
}
}
impl SerError for Error {
fn custom<T: Display>(msg: T) -> Self {
ErrorKind::Custom(msg.to_string()).into()
}
}
|
// Copyright 2023 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::any::Any;
use std::sync::Arc;
use common_exception::Result;
use crate::processors::port::InputPort;
use crate::processors::port::OutputPort;
use crate::processors::processor::Event;
use crate::processors::Processor;
pub struct ShuffleProcessor {
channel: Vec<(Arc<InputPort>, Arc<OutputPort>)>,
}
impl ShuffleProcessor {
pub fn create(
inputs: Vec<Arc<InputPort>>,
outputs: Vec<Arc<OutputPort>>,
rule: Vec<usize>,
) -> Self {
let len = rule.len();
debug_assert!({
let mut sorted = rule.clone();
sorted.sort();
let expected = (0..len).collect::<Vec<_>>();
sorted == expected
});
let mut channel = Vec::with_capacity(len);
for (i, input) in inputs.into_iter().enumerate() {
let output = outputs[rule[i]].clone();
channel.push((input, output));
}
ShuffleProcessor { channel }
}
}
#[async_trait::async_trait]
impl Processor for ShuffleProcessor {
fn name(&self) -> String {
"Shuffle".to_string()
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
fn event(&mut self) -> Result<Event> {
let mut finished = true;
for (input, output) in self.channel.iter() {
if output.is_finished() || input.is_finished() {
input.finish();
output.finish();
continue;
}
finished = false;
input.set_need_data();
if output.can_push() && input.has_data() {
output.push_data(input.pull_data().unwrap());
}
}
if finished {
return Ok(Event::Finished);
}
Ok(Event::NeedData)
}
}
|
use std::ffi::CString;
use std::marker::PhantomData;
use std::mem::ManuallyDrop;
use gdal_sys::{VSIFCloseL, VSIFileFromMemBuffer, VSIFree, VSIGetMemFileBuffer, VSIUnlink};
use crate::errors::{GdalError, Result};
use crate::utils::_last_null_pointer_err;
/// Creates a new VSIMemFile from a given buffer.
pub fn create_mem_file(file_name: &str, data: Vec<u8>) -> Result<()> {
let file_name = CString::new(file_name)?;
// ownership will be given to GDAL, so it should not be automaticly dropped
let mut data = ManuallyDrop::new(data);
let handle = unsafe {
VSIFileFromMemBuffer(
file_name.as_ptr(),
data.as_mut_ptr(),
data.len() as u64,
true as i32,
)
};
if handle.is_null() {
// on error, allow dropping the data again
ManuallyDrop::into_inner(data);
return Err(_last_null_pointer_err("VSIGetMemFileBuffer"));
}
unsafe {
VSIFCloseL(handle);
}
Ok(())
}
/// A helper struct that unlinks a mem file that points to borrowed data
/// before that data is freed.
pub struct MemFileRef<'d> {
file_name: String,
data_ref: PhantomData<&'d mut ()>,
}
impl<'d> MemFileRef<'d> {
pub fn new(file_name: &str) -> MemFileRef<'d> {
Self {
file_name: file_name.to_string(),
data_ref: PhantomData::default(),
}
}
}
impl<'d> Drop for MemFileRef<'d> {
fn drop(&mut self) {
// try to unlink file
// if it fails, ignore - it probably was manually unlinked before
let _ = unlink_mem_file(&self.file_name);
}
}
/// Creates a new VSIMemFile from a given buffer reference.
/// Returns a handle that has a lifetime that is shorter than `data`.
pub fn create_mem_file_from_ref<'d>(file_name: &str, data: &'d mut [u8]) -> Result<MemFileRef<'d>> {
let file_name_c = CString::new(file_name)?;
let handle = unsafe {
VSIFileFromMemBuffer(
file_name_c.as_ptr(),
data.as_mut_ptr(),
data.len() as u64,
false as i32,
)
};
if handle.is_null() {
return Err(_last_null_pointer_err("VSIGetMemFileBuffer"));
}
unsafe {
VSIFCloseL(handle);
}
Ok(MemFileRef::new(file_name))
}
/// Unlink a VSIMemFile.
pub fn unlink_mem_file(file_name: &str) -> Result<()> {
let file_name_c = CString::new(file_name)?;
let rv = unsafe { VSIUnlink(file_name_c.as_ptr()) };
if rv != 0 {
return Err(GdalError::UnlinkMemFile {
file_name: file_name.to_string(),
});
}
Ok(())
}
/// Copies the bytes of the VSIMemFile with given `file_name`.
/// Takes the ownership and frees the memory of the VSIMemFile.
pub fn get_vsi_mem_file_bytes_owned(file_name: &str) -> Result<Vec<u8>> {
let file_name = CString::new(file_name)?;
let owned_bytes = unsafe {
let mut length: u64 = 0;
let bytes = VSIGetMemFileBuffer(file_name.as_ptr(), &mut length, true as i32);
if bytes.is_null() {
return Err(_last_null_pointer_err("VSIGetMemFileBuffer"));
}
let slice = std::slice::from_raw_parts(bytes, length as usize);
let vec = slice.to_vec();
VSIFree(bytes.cast::<std::ffi::c_void>());
vec
};
Ok(owned_bytes)
}
/// Computes a function on the bytes of the vsi in-memory file with given `file_name`.
/// This method is useful if you don't want to take the ownership of the memory.
pub fn call_on_mem_file_bytes<F, R>(file_name: &str, fun: F) -> Result<R>
where
F: FnOnce(&[u8]) -> R,
{
let file_name = CString::new(file_name)?;
unsafe {
let mut length: u64 = 0;
let bytes = VSIGetMemFileBuffer(file_name.as_ptr(), &mut length, false as i32);
if bytes.is_null() {
return Err(_last_null_pointer_err("VSIGetMemFileBuffer"));
}
let slice = std::slice::from_raw_parts(bytes, length as usize);
Ok(fun(slice))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_and_retrieve_mem_file() {
let file_name = "/vsimem/525ebf24-a030-4677-bb4e-a921741cabe0";
create_mem_file(file_name, vec![1_u8, 2, 3, 4]).unwrap();
let bytes = get_vsi_mem_file_bytes_owned(file_name).unwrap();
assert_eq!(bytes, vec![1_u8, 2, 3, 4]);
// mem file must not be there anymore
assert_eq!(
unlink_mem_file(file_name),
Err(GdalError::UnlinkMemFile {
file_name: file_name.to_string()
})
);
}
#[test]
fn create_and_callmem_file() {
let file_name = "/vsimem/ee08caf2-a510-4b21-a4c4-44c1ebd763c8";
create_mem_file(file_name, vec![1_u8, 2, 3, 4]).unwrap();
let result = call_on_mem_file_bytes(file_name, |bytes| {
bytes.iter().map(|b| b * 2).collect::<Vec<u8>>()
})
.unwrap();
assert_eq!(result, vec![2_u8, 4, 6, 8]);
unlink_mem_file(file_name).unwrap();
}
#[test]
fn create_and_unlink_mem_file() {
let file_name = "/vsimem/bbf5f1d6-c1e9-4469-a33b-02cd9173132d";
create_mem_file(file_name, vec![1_u8, 2, 3, 4]).unwrap();
unlink_mem_file(file_name).unwrap();
}
#[test]
fn no_mem_file() {
assert_eq!(
get_vsi_mem_file_bytes_owned("foobar"),
Err(GdalError::NullPointer {
method_name: "VSIGetMemFileBuffer",
msg: "".to_string(),
})
);
}
#[test]
fn create_and_unlink_mem_file_from_ref() {
let file_name = "/vsimem/58e61d06-c96b-4ac0-9dd5-c37f69508454";
let mut data = vec![1_u8, 2, 3, 4];
let ref_handle = create_mem_file_from_ref(file_name, &mut data).unwrap();
drop(ref_handle);
// data was not corrupted
assert_eq!(data, vec![1_u8, 2, 3, 4]);
}
#[test]
fn mem_file_ref_double_unlink() {
let file_name = "/vsimem/86df94a7-051d-4582-b141-d705ba8d8e83";
let mut data = vec![1_u8, 2, 3, 4];
let ref_handle = create_mem_file_from_ref(file_name, &mut data).unwrap();
unlink_mem_file(file_name).unwrap();
drop(ref_handle);
}
#[test]
fn unable_to_create() {
let file_name = "";
assert_eq!(
create_mem_file(file_name, vec![1_u8, 2, 3, 4]),
Err(GdalError::NullPointer {
method_name: "VSIGetMemFileBuffer",
msg: "".to_string(),
})
);
assert_eq!(
unlink_mem_file(file_name),
Err(GdalError::UnlinkMemFile {
file_name: "".to_string()
})
);
}
}
|
use aoc2019::aoc_input::get_input;
use aoc2019::intcode::*;
use std::ops::Index;
use std::str::FromStr;
#[derive(Debug, Copy, Clone, PartialEq)]
enum Tile {
OpenSpace,
Scaffolding,
}
type Coordinate = (usize, usize);
struct Map {
grid: Vec<Tile>,
width: usize,
}
impl Map {
fn height(&self) -> usize {
self.grid.len() / self.width
}
fn width(&self) -> usize {
self.width
}
}
impl Index<Coordinate> for Map {
type Output = Tile;
fn index(&self, index: Coordinate) -> &Self::Output {
self.grid.index(self.width * index.1 + index.0)
}
}
impl FromStr for Map {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut grid = Vec::<Tile>::new();
let mut width: Option<usize> = None;
for line in s.trim().lines() {
let mut row = Vec::<Tile>::with_capacity(line.len());
for c in line.chars() {
let tile = match c {
'.' => Tile::OpenSpace,
'#' | 'v' | '^' | '<' | '>' => Tile::Scaffolding,
_ => return Err("Invalid character in string"),
};
row.push(tile);
}
if width.is_some() && width.unwrap() != row.len() {
return Err("Line length is not uniform");
}
width = Some(row.len());
grid.extend(row);
}
if width.is_none() || width.unwrap() == 0 {
return Err("Empty string");
}
Ok(Map {
grid,
width: width.unwrap(),
})
}
}
fn sum_alignment_parameters(tape: Tape) -> usize {
let mut machine = IntcodeMachine::new(tape);
machine.run_to_completion().unwrap();
let output: String = machine
.output
.borrow_mut()
.drain(..)
.map(|n| std::char::from_u32(n as u32).unwrap())
.collect();
print!("{}", output);
let map: Map = output.parse().unwrap();
let mut alignment = 0usize;
for y in 1..map.height() - 1 {
for x in 1..map.width() - 1 {
if map[(x, y)] != Tile::Scaffolding {
continue;
}
let adjacent = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)];
if adjacent
.iter()
.copied()
.all(|c| map[c] == Tile::Scaffolding)
{
alignment += x * y;
}
}
}
alignment
}
fn main() {
let input = get_input(17);
let tape = parse_intcode_program(&input);
let alignment = sum_alignment_parameters(tape.clone());
println!("Sum of alignment parameters: {}", alignment);
}
|
//! High-speed timer
//!
//! Size: 4K
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut};
use static_assertions::const_assert_eq;
pub const PADDR: usize = 0x01C6_0000;
register! {
IrqEnable,
u32,
RW,
Fields [
Enable WIDTH(U1) OFFSET(U0)
]
}
register! {
IrqStatus,
u32,
RW,
Fields [
IrqPending WIDTH(U1) OFFSET(U0)
]
}
register! {
Control,
u32,
RW,
Fields [
Enable WIDTH(U1) OFFSET(U0),
Reload WIDTH(U1) OFFSET(U1),
Prescale WIDTH(U3) OFFSET(U4) [
Div1 = U0,
Div2 = U1,
Div4 = U2,
Div8 = U3,
Div16 = U4
],
Mode WIDTH(U1) OFFSET(U7) [
Continuous = U0,
OneShot = U1
]
]
}
register! {
IntervalLow,
u32,
RW,
Fields [
Value WIDTH(U32) OFFSET(U0)
]
}
register! {
IntervalHigh,
u32,
RW,
Fields [
Value WIDTH(U24) OFFSET(U0)
]
}
register! {
CurrentLow,
u32,
RW,
Fields [
Value WIDTH(U32) OFFSET(U0)
]
}
register! {
CurrentHigh,
u32,
RW,
Fields [
Value WIDTH(U24) OFFSET(U0)
]
}
const_assert_eq!(core::mem::size_of::<RegisterBlock>(), 0x24);
#[repr(C)]
pub struct RegisterBlock {
pub irq_enable: IrqEnable::Register, // 0x00
pub irq_status: IrqStatus::Register, // 0x04
__reserved_0: [u32; 2], // 0x08
pub ctrl: Control::Register, // 0x10
pub intv_lo: IntervalLow::Register, // 0x14
pub intv_hi: IntervalHigh::Register, // 0x18
pub cval_lo: CurrentLow::Register, // 0x1C
pub cval_hi: CurrentHigh::Register, // 0x20
}
pub struct HSTIMER {
_marker: PhantomData<*const ()>,
}
unsafe impl Send for HSTIMER {}
impl HSTIMER {
pub unsafe fn from_paddr() -> Self {
Self {
_marker: PhantomData,
}
}
pub fn as_ptr(&self) -> *const RegisterBlock {
PADDR as *const _
}
pub const unsafe fn ptr() -> *const RegisterBlock {
PADDR as *const _
}
pub fn as_mut_ptr(&mut self) -> *mut RegisterBlock {
PADDR as *mut _
}
pub const unsafe fn mut_ptr() -> *mut RegisterBlock {
PADDR as *mut _
}
}
impl Deref for HSTIMER {
type Target = RegisterBlock;
fn deref(&self) -> &RegisterBlock {
unsafe { &*self.as_ptr() }
}
}
impl DerefMut for HSTIMER {
fn deref_mut(&mut self) -> &mut RegisterBlock {
unsafe { &mut *self.as_mut_ptr() }
}
}
|
use super::InternalEvent;
use metrics::counter;
use std::borrow::Cow;
use string_cache::DefaultAtom as Atom;
#[derive(Debug)]
pub struct RegexEventProcessed;
impl InternalEvent for RegexEventProcessed {
fn emit_metrics(&self) {
counter!("events_processed", 1,
"component_kind" => "transform",
"component_type" => "regex_parser",
);
}
}
#[derive(Debug)]
pub struct RegexFailedMatch<'a> {
pub value: &'a [u8],
}
impl InternalEvent for RegexFailedMatch<'_> {
fn emit_logs(&self) {
warn!(
message = "regex pattern failed to match.",
field = &truncate_string_at(&String::from_utf8_lossy(&self.value), 60)[..],
rate_limit_secs = 30
);
}
fn emit_metrics(&self) {
counter!("processing_error", 1,
"component_kind" => "transform",
"component_type" => "regex_parser",
"error_type" => "failed_match",
);
}
}
#[derive(Debug)]
pub struct RegexMissingField<'a> {
pub field: &'a Atom,
}
impl InternalEvent for RegexMissingField<'_> {
fn emit_logs(&self) {
debug!(message = "field does not exist.", field = %self.field);
}
fn emit_metrics(&self) {
counter!("processing_error", 1,
"component_kind" => "transform",
"component_type" => "regex_parser",
"error_type" => "missing_field",
);
}
}
const ELLIPSIS: &str = "[...]";
fn truncate_string_at(s: &str, maxlen: usize) -> Cow<str> {
if s.len() >= maxlen {
let mut len = maxlen - ELLIPSIS.len();
while !s.is_char_boundary(len) {
len -= 1;
}
format!("{}{}", &s[..len], ELLIPSIS).into()
} else {
s.into()
}
}
#[cfg(test)]
mod test {
#[test]
fn truncate_utf8() {
let message = "hello 😁 this is test";
assert_eq!("hello [...]", super::truncate_string_at(&message, 13));
}
}
|
#![allow(dead_code)]
#[macro_use] extern crate derivative;
// #[cfg(test)]
// #[macro_use]
// extern crate pretty_assertions;
#[macro_use] extern crate lazy_static;
use crate::data_ini::DataIni;
use crate::globals::*;
use crate::slk_datas::SLKData;
pub const PREFIX_SAMPLE_PATH: &str = "resources/sample_1";
pub const PREFIX_MDL_PATH: &str = "resources/blp";
pub const PREFIX_BLP_PATH: &str = "resources/mdl";
pub fn concat_path(path: &str) -> String{
format!("{}/{}",PREFIX_SAMPLE_PATH, path)
}
#[derive(Clone, Debug, PartialEq)]
pub enum OpeningError {
Protected(String),
Environment(String),
CustomTextTrigger(String),
Triggers(String),
Import(String),
Minimap(String),
MenuMinimap(String),
PathingMap(String),
Region(String),
ShadowMap(String),
Doodad(String),
Camera(String),
UnitItem(String),
Sound(String),
MapStrings(String),
Info(String),
CustomUnit(String),
CustomItem(String),
CustomAbility(String),
CustomBuff(String),
CustomUpgrade(String),
CustomDoodad(String),
CustomDestructable(String),
}
pub fn format_data(prefix: &str, path: &str) -> String{
format!("{}resources/datas/{}", prefix, path)
}
pub fn format_slk(prefix: &str, path: &str) -> String{
format!("{}resources/slk/{}", prefix, path)
}
pub struct GameData{
trigger_data: DataIni,
unit_data: SLKData,
unit_meta: SLKData,
doodad_meta: SLKData,
destructable_meta: SLKData,
abilty_meta: SLKData,
upgrade_meta: SLKData,
upgrade_effect_meta: SLKData,
const_meta: SLKData,
ui_const_meta: SLKData,
ability_buff_meta: SLKData,
ability_data: SLKData,
upgrade_data: SLKData,
doodad_effect_data: SLKData,
destructable_effect_data: SLKData,
}
impl GameData {
pub fn new(prefix: &str) -> Self{
let mut trigger_data = DataIni::new();
trigger_data.merge(&format_data( prefix,PROFILE_TRIGGER_DATA));
let unit_meta = SLKData::load(&format_slk(prefix, SLK_UNIT_META_DATA));
let doodad_meta = SLKData::load(&format_slk(prefix, SLK_DOODAD_META_DATA));
let destructable_meta = SLKData::load(&format_slk(prefix, SLK_DESTRUCTABLE_META_DATA));
let abilty_meta = SLKData::load(&format_slk(prefix, SLK_ABILITY_META_DATA));
let upgrade_meta = SLKData::load(&format_slk(prefix, SLK_UPGRADE_META_DATA));
let upgrade_effect_meta = SLKData::load(&format_slk(prefix, SLK_UPGRADE_EFFECT_META_DATA));
let const_meta = SLKData::load(&format_slk(prefix, SLK_MISC_META_DATA));
let ui_const_meta = SLKData::load(&format_slk(prefix, SLK_SKIN_META_DATA));
let ability_buff_meta = SLKData::load(&format_slk(prefix, SLK_ABILITY_BUFF_META_DATA));
let mut unit_data = SLKData::new();
unit_data.merge(&format_slk(prefix, SLK_UNIT_DATA));
unit_data.merge(&format_slk(prefix, SLK_UNIT_BALANCE));
unit_data.merge(&format_slk(prefix, SLK_UNIT_UI));
unit_data.merge(&format_slk(prefix, SLK_UNIT_ABILITIES));
unit_data.merge(&format_slk(prefix, SLK_UNIT_WEAPONS));
let ability_data = SLKData::load(&format_slk(prefix, SLK_ABILITY_DATA));
let upgrade_data = SLKData::load(&format_slk(prefix, SLK_UPGRADE_DATA));
let doodad_effect_data = SLKData::load(&format_slk(prefix, SLK_DOODADS));
let destructable_effect_data = SLKData::load(&format_slk(prefix, SLK_DESTRUCTABLE_DATA));
Self{
trigger_data,
unit_data,
unit_meta,
doodad_meta,
destructable_meta,
abilty_meta,
upgrade_meta,
upgrade_effect_meta,
const_meta,
ui_const_meta,
ability_buff_meta,
ability_data,
upgrade_data,
doodad_effect_data,
destructable_effect_data,
}
}
pub fn get_trigger_data(&self) -> &DataIni{ &self.trigger_data }
}
pub mod error;
pub mod globals;
pub mod w3i_file;
pub mod mmp_file;
pub mod region_file;
pub mod camera_file;
pub mod sound_file;
pub mod pathmap_file;
pub mod shadowmap_file;
pub mod terrain_file;
pub mod minimap_file;
pub mod import_file;
pub mod trigger_string_file;
pub mod trigger_jass_file;
pub mod triggers;
pub mod map;
pub mod slk_datas;
pub mod data_ini;
pub mod doodad_map;
pub mod unit_map;
pub mod custom_datas;
|
// 1xx: Positive Preliminary Reply
pub const INITIATING: u32 = 100;
pub const RESTART_MARKER: u32 = 110;
pub const READY_MINUTE: u32 = 120;
pub const ALREADY_OPEN: u32 = 125;
pub const ABOUT_TO_SEND: u32 = 150;
// 2xx: Positive Completion Reply
pub const COMMAND_OK: u32 = 200;
pub const COMMAND_NOT_IMPLEMENTED: u32 = 202;
pub const SYSTEM: u32 = 211;
pub const DIRECTORY: u32 = 212;
pub const FILE: u32 = 213;
pub const HELP: u32 = 214;
pub const NAME: u32 = 215;
pub const READY: u32 = 220;
pub const CLOSING: u32 = 221;
pub const DATA_CONNECTION_OPEN: u32 = 225;
pub const CLOSING_DATA_CONNECTION: u32 = 226;
pub const PASSIVE_MODE: u32 = 227;
pub const LONG_PASSIVE_MODE: u32 = 228;
pub const EXTENDED_PASSIVE_MODE: u32 = 229;
pub const LOGGED_IN: u32 = 230;
pub const LOGGED_OUT: u32 = 231;
pub const LOGOUT_ACK: u32 = 232;
pub const AUTH_OK: u32 = 234;
pub const REQUESTED_FILE_ACTION_OK: u32 = 250;
pub const PATH_CREATED: u32 = 257;
// 3xx: Positive intermediate Reply
pub const NEED_PASSWORD: u32 = 331;
pub const LOGIN_NEED_ACCOUNT: u32 = 332;
pub const REQUEST_FILE_PENDING: u32 = 350;
// 4xx: Transient Negative Completion Reply
pub const NOT_AVAILABLE: u32 = 421;
pub const CANNOT_OPEN_DATA_CONNECTION: u32 = 425;
pub const TRANSER_ABORTED: u32 = 426;
pub const INVALID_CREDENTIALS: u32 = 430;
pub const HOST_UNAVAILABLE: u32 = 434;
pub const REQUEST_FILE_ACTION_IGNORED: u32 = 450;
pub const ACTION_ABORTED: u32 = 451;
pub const REQUESTED_ACTION_NOT_TAKEN: u32 = 452;
// 5xx: Permanent Negative Completion Reply
pub const BAD_COMMAND: u32 = 500;
pub const BAD_ARGUMENTS: u32 = 501;
pub const NOT_IMPLEMENTED: u32 = 502;
pub const BAD_SEQUENCE: u32 = 503;
pub const NOT_IMPLEMENTED_PARAMETER: u32 = 504;
pub const NOT_LOGGED_IN: u32 = 530;
pub const STORING_NEED_ACCOUNT: u32 = 532;
pub const FILE_UNAVAILABLE: u32 = 550;
pub const PAGE_TYPE_UNKNOWN: u32 = 551;
pub const EXCEEDED_STORAGE: u32 = 552;
pub const BAD_FILENAME: u32 = 553;
|
//
//
//
//! Achitecture-specific code
cfg_if::cfg_if!{
if #[cfg(feature="test")] {
#[macro_use]
#[path="imp-test.rs"]
#[doc(hidden)]
pub mod imp;
}
else {
#[macro_use]
//#[cfg_attr(arch="amd64", path="amd64/mod.rs")]
#[cfg_attr(target_arch="x86_64", path="amd64/mod.rs")]
#[cfg_attr(arch="armv7", path="armv7/mod.rs")]
#[cfg_attr(target_arch="arm", path="armv7/mod.rs")]
#[cfg_attr(target_arch="aarch64", path="armv8/mod.rs")]
#[cfg_attr(arch="armv8", path="armv8/mod.rs")]
#[cfg_attr(target_arch="riscv64", path="riscv64/mod.rs")]
#[doc(hidden)]
pub mod imp; // Needs to be pub for exports to be avaliable
}
}
// If on x86/amd64, import ACPI
#[cfg(not(feature="test"))]
#[cfg(any(arch="amd64", target_arch="x86_64"))]
pub use self::imp::acpi;
/// Memory management
pub mod memory {
/// Physical address type
pub type PAddr = ::arch::imp::memory::PAddr;
pub type VAddr = ::arch::imp::memory::VAddr;
/// Size of a page/frame in bytes (always a power of two)
pub const PAGE_SIZE: usize = ::arch::imp::memory::PAGE_SIZE;
/// Offset mask for a page
pub const PAGE_MASK: usize = PAGE_SIZE-1;
/// Address space layout
pub mod addresses {
use arch::imp::memory::addresses as imp;
#[inline]
/// Returns `true` if the passed address is valid in every address space
pub fn is_global(addr: usize) -> bool {
imp::is_global(addr)
}
/// Size of a single kernel statck
pub const STACK_SIZE: usize = imp::STACK_SIZE;
/// Last first address after the user-controlled region
pub const USER_END: usize = imp::USER_END;
/// Start of the kernel stack region
pub const STACKS_BASE: usize = imp::STACKS_BASE;
/// End of the kernel stack region
pub const STACKS_END : usize = imp::STACKS_END ;
/// Start of hardware mappings
pub const HARDWARE_BASE: usize = imp::HARDWARE_BASE;
/// End of hardware mappings
pub const HARDWARE_END : usize = imp::HARDWARE_END ;
/// Start of the heap reservation
pub const HEAP_START: usize = imp::HEAP_START;
/// End of the heap reservation
pub const HEAP_END : usize = imp::HEAP_END ;
pub const BUMP_START: usize = imp::BUMP_START;
pub const BUMP_END: usize = imp::BUMP_END;
pub const PMEMREF_BASE: usize = imp::PMEMREF_BASE;
pub const PMEMREF_END : usize = imp::PMEMREF_END;
pub const PMEMBM_BASE: usize = imp::PMEMBM_BASE;
pub const PMEMBM_END : usize = imp::PMEMBM_END;
}
/// Virtual memory manipulation
pub mod virt {
use arch::imp::memory::virt as imp;
/// Handle to an address space
#[derive(Debug)]
pub struct AddressSpace(imp::AddressSpace);
impl AddressSpace
{
pub fn new(clone_start: usize, clone_end: usize) -> Result<AddressSpace,::memory::virt::MapError> {
imp::AddressSpace::new(clone_start, clone_end).map(AddressSpace)
}
pub fn pid0() -> AddressSpace {
AddressSpace(imp::AddressSpace::pid0())
}
pub fn inner(&self) -> &imp::AddressSpace {
&self.0
}
}
/// A handle to a temproarily mapped frame containing instances of 'T'
// TODO: TempHandle doens't own the mapped frame - It probably should
pub struct TempHandle<T>(*mut T);
impl<T> TempHandle<T>
{
/// UNSAFE: User must ensure that address is valid, and that no aliasing occurs
pub unsafe fn new(phys: ::arch::memory::PAddr) -> TempHandle<T> {
TempHandle( imp::temp_map(phys) )
}
/// Cast to another type
pub fn into<U>(self) -> TempHandle<U> {
let rv = TempHandle( self.0 as *mut U );
::core::mem::forget(self);
rv
}
pub fn phys_addr(&self) -> ::memory::PAddr {
get_phys(self.0)
}
}
impl<T: ::lib::POD> ::core::ops::Deref for TempHandle<T> {
type Target = [T];
fn deref(&self) -> &[T] {
// SAFE: We should have unique access, and data is POD
unsafe { ::core::slice::from_raw_parts(self.0, ::PAGE_SIZE / ::core::mem::size_of::<T>()) }
}
}
impl<T: ::lib::POD> ::core::ops::DerefMut for TempHandle<T> {
fn deref_mut(&mut self) -> &mut [T] {
// SAFE: We should have unique access, and data is POD
unsafe { ::core::slice::from_raw_parts_mut(self.0, ::PAGE_SIZE / ::core::mem::size_of::<T>()) }
}
}
impl<T> ::core::ops::Drop for TempHandle<T> {
fn drop(&mut self) {
// SAFE: Address came from a call to temp_map
unsafe {
imp::temp_unmap(self.0);
}
}
}
pub fn post_init() {
imp::post_init()
}
#[inline]
pub fn get_phys<T: ?Sized>(p: *const T) -> ::memory::PAddr {
imp::get_phys(p as *const ())
}
#[inline]
pub fn is_reserved<T>(p: *const T) -> bool {
imp::is_reserved(p)
}
#[inline]
pub fn get_info<T>(p: *const T) -> Option<(::memory::PAddr,::memory::virt::ProtectionMode)> {
imp::get_info(p)
}
#[inline]
pub fn is_fixed_alloc(addr: *const (), size: usize) -> bool {
imp::is_fixed_alloc(addr, size)
}
#[inline]
pub unsafe fn fixed_alloc(p: ::memory::PAddr, count: usize) -> Option<*mut ()> {
imp::fixed_alloc(p, count)
}
#[inline]
/// Returns `true` if the provided address can have `map` called on without needing memory allocation
// Used in physical memory allocation to avoid recursion
pub fn can_map_without_alloc(a: *mut ()) -> bool {
imp::can_map_without_alloc(a)
}
#[inline]
pub unsafe fn map(a: *mut (), p: ::memory::PAddr, mode: ::memory::virt::ProtectionMode) {
imp::map(a, p, mode)
}
#[inline]
pub unsafe fn reprotect(a: *mut (), mode: ::memory::virt::ProtectionMode) {
imp::reprotect(a, mode)
}
#[inline]
pub unsafe fn unmap(a: *mut ()) -> Option<::memory::PAddr> {
imp::unmap(a)
}
}
}
/// Syncronisation types (spinlock and interrupt holding)
pub mod sync {
use super::imp::sync as imp;
/// Lightweight protecting spinlock
pub struct Spinlock<T>
{
#[doc(hidden)]
/*pub*/ lock: imp::SpinlockInner,
#[doc(hidden)]
pub value: ::core::cell::UnsafeCell<T>,
}
unsafe impl<T: Send> Sync for Spinlock<T> {}
impl<T> Spinlock<T>
{
/// Create a new spinning lock
pub const fn new(val: T) -> Spinlock<T> {
Spinlock {
lock: imp::SpinlockInner::new(),
value: ::core::cell::UnsafeCell::new(val),
}
}
pub fn get_mut(&mut self) -> &mut T {
// SAFE: &mut to lock
unsafe { &mut *self.value.get() }
}
/// Lock this spinning lock
//#[not_safe(irq)]
pub fn lock(&self) -> HeldSpinlock<T>
{
self.lock.inner_lock();
HeldSpinlock { lock: self }
}
/// Lock this spinning lock (accepting risk of panick/deadlock from IRQs)
//#[is_safe(irq)]
pub fn lock_irqsafe(&self) -> HeldSpinlock<T> {
self.lock.inner_lock();
HeldSpinlock { lock: self }
}
/// Attempt to acquire the lock, returning None if it is already held by this CPU
//#[is_safe(irq)]
pub fn try_lock_cpu(&self) -> Option<HeldSpinlock<T>>
{
if self.lock.try_inner_lock_cpu()
{
Some( HeldSpinlock { lock: self } )
}
else
{
None
}
}
}
// Some special functions on non-wrapping spinlocks
impl Spinlock<()>
{
pub unsafe fn unguarded_lock(&self) {
self.lock.inner_lock()
}
pub unsafe fn unguarded_release(&self) {
self.lock.inner_release()
}
}
impl<T: Default> Default for Spinlock<T>
{
fn default() -> Self {
Spinlock::new(Default::default())
}
}
pub struct HeldSpinlock<'lock, T: 'lock>
{
lock: &'lock Spinlock<T>,
}
impl<'lock,T> ::core::ops::Drop for HeldSpinlock<'lock, T>
{
fn drop(&mut self)
{
// SAFE: This is the RAII handle for the lock
unsafe {
self.lock.lock.inner_release();
}
}
}
impl<'lock,T> ::core::ops::Deref for HeldSpinlock<'lock, T>
{
type Target = T;
fn deref(&self) -> &T {
// SAFE: & to handle makes & to value valid
unsafe { &*self.lock.value.get() }
}
}
impl<'lock,T> ::core::ops::DerefMut for HeldSpinlock<'lock, T>
{
fn deref_mut(&mut self) -> &mut T {
// SAFE: &mut to handle makes &mut to value valid
unsafe { &mut *self.lock.value.get() }
}
}
pub type HeldInterrupts = imp::HeldInterrupts;
#[inline]
/// Halt interrupts and return a RAII handle
pub fn hold_interrupts() -> HeldInterrupts {
imp::hold_interrupts()
}
/// UNSAFE: Not strictly speaking...
pub unsafe fn stop_interrupts() {
imp::stop_interrupts()
}
/// UNSAFE: Can be used to break `hold_interrupts`, and other related assumptions
pub unsafe fn start_interrupts() {
imp::start_interrupts()
}
}
pub mod interrupts {
use super::imp::interrupts as imp;
/// Architecture-specific IRQ binding error type
pub type BindError = imp::BindError;
/// IRQ handle (unbinds the IRQ when dropped)
#[derive(Default)]
pub struct IRQHandle(imp::IRQHandle);
impl IRQHandle {
///// Disable/mask-off this IRQ (for when processing is scheduled)
//pub fn disable(&self) {
//}
///// Enable/mask-on this IRQ (for when processing is complete)
//pub fn enable(&self) {
//}
}
#[inline]
/// Attach a callback to an IRQ/interrupt
pub fn bind_gsi(gsi: usize, handler: fn(*const()), info: *const ()) -> Result<IRQHandle, BindError> {
imp::bind_gsi(gsi, handler, info).map(|v| IRQHandle(v))
}
}
pub mod boot {
use super::imp::boot as imp;
#[inline]
pub fn get_boot_string() -> &'static str {
imp::get_boot_string()
}
#[inline]
pub fn get_video_mode() -> Option<::metadevs::video::bootvideo::VideoMode> {
imp::get_video_mode()
}
#[inline]
pub fn get_memory_map() -> &'static [::memory::MemoryMapEnt] {
imp::get_memory_map()
}
}
pub mod threads {
use super::imp::threads as imp;
pub type State = imp::State;
#[inline]
pub fn init_tid0_state() -> State {
imp::init_tid0_state()
}
#[inline]
pub fn set_thread_ptr(t: ::threads::ThreadPtr) {
imp::set_thread_ptr(t)
}
#[inline]
pub fn get_thread_ptr() -> Option<::threads::ThreadPtr> {
imp::get_thread_ptr()
}
#[inline]
pub fn borrow_thread() -> *const ::threads::Thread {
imp::borrow_thread()
}
#[inline]
pub fn idle(held_interrupts: super::sync::HeldInterrupts) {
imp::idle(held_interrupts)
}
#[inline]
pub fn get_idle_thread() -> ::threads::ThreadPtr {
imp::get_idle_thread()
}
#[inline]
pub fn switch_to(t: ::threads::ThreadPtr) {
imp::switch_to(t)
}
#[inline]
pub fn start_thread<F: FnOnce()+Send+'static>(thread: &mut ::threads::Thread, code: F) {
imp::start_thread(thread, code)
}
}
/// x86 IO bus accesses
pub mod x86_io {
use super::imp::x86_io as imp;
#[inline]
pub unsafe fn inb(p: u16) -> u8 { imp::inb(p) }
#[inline]
pub unsafe fn inw(p: u16) -> u16 { imp::inw(p) }
#[inline]
pub unsafe fn inl(p: u16) -> u32 { imp::inl(p) }
#[inline]
pub unsafe fn outb(p: u16, v: u8) { imp::outb(p, v) }
#[inline]
pub unsafe fn outw(p: u16, v: u16) { imp::outw(p, v) }
#[inline]
pub unsafe fn outl(p: u16, v: u32) { imp::outl(p, v) }
}
#[inline]
pub fn puts(s: &str) {
imp::puts(s);
}
#[inline]
pub fn puth(v: u64) {
imp::puth(v)
}
#[inline]
pub fn cur_timestamp() -> u64 {
imp::cur_timestamp()
}
#[inline]
pub fn print_backtrace() {
imp::print_backtrace()
}
#[inline]
pub unsafe fn drop_to_user(entry: usize, stack: usize, args_len: usize) -> ! {
imp::drop_to_user(entry, stack, args_len)
}
|
use std::cmp::Ordering;
fn main() {
let input: Vec<&str> = include_str!("./input_a.txt").lines().collect();
let mut asteroids: Vec<Point> = Vec::new();
for (y, &line) in input.iter().enumerate() {
for (x, ch) in line.char_indices() {
if ch == '#' {
asteroids.push(Point::new(x as f32, y as f32));
}
}
}
let mut counts: Vec<Vec<f32>> = Vec::new();
for asteroid in asteroids.iter() {
let mut set: Vec<f32> = Vec::new();
for b in asteroids.iter() {
if asteroid.x != b.x || asteroid.y != b.y {
let angle = asteroid.angle(b);
if !set.contains(&angle) {
set.push(angle);
}
}
}
counts.push(set);
}
let mut highest = 0;
let mut station_idx = 0;
for (i, c) in counts.iter().enumerate() {
if c.len() > highest {
highest = c.len();
station_idx = i;
}
}
let station = &asteroids[station_idx];
println!("{}", highest);
println!("{:?}", station);
let mut station_angles: Vec<(&Point, f32, bool)> = Vec::new();
for b in asteroids.iter() {
if station.x == b.x && station.y == b.y {
} else {
let angle = station.angle(b);
station_angles.push((b, angle, false));
}
}
station_angles.sort_by(|a,b| a.1.partial_cmp(&b.1).unwrap_or(Ordering::Equal));
let mut last_angle: f32 = -0.1;
let mut count = 0;
let mut idx = 0;
while count < 203 {
let mut el = &mut station_angles[idx];
if el.1 != last_angle && !el.2{
last_angle = el.1;
count += 1;
el.2 = true;
println!("{} {:?}", count, el);
} else {
if !el.2 {
println!("Skipping {:?}", el);
}
}
idx = (idx + 1) % station_angles.len();
}
println!("{:?}", station_angles[idx-1]);
println!("{:?}", (station_angles[idx-1].0.x * 100.0) + station_angles[idx-1].0.y)
}
#[derive(Debug)]
struct Point {
x: f32,
y: f32
}
impl Point {
fn new(x: f32, y: f32) -> Point {
Point { x, y }
}
fn angle(&self, p2: &Point) -> f32 {
let delta_x = p2.x - self.x;
let delta_y = p2.y - self.y;
let mut r = delta_x.atan2(delta_y) * (-180.0 / std::f32::consts::PI);
r = r - 180.0;
((r % 360.0) + 360.0) % 360.0
}
}
|
#[doc = "Reader of register EPHYRIS"]
pub type R = crate::R<u32, super::EPHYRIS>;
#[doc = "Reader of field `INT`"]
pub type INT_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - Ethernet PHY Raw Interrupt Status"]
#[inline(always)]
pub fn int(&self) -> INT_R {
INT_R::new((self.bits & 0x01) != 0)
}
}
|
use front::stdlib::value::{Value, ResultValue, ToValue, FromValue, to_value, from_value};
use front::stdlib::function::Function;
use std::collections::btree_map::BTreeMap;
pub static PROTOTYPE: &'static str = "prototype";
pub static INSTANCE_PROTOTYPE: &'static str = "__proto__";
//#[derive(Clone)]
pub type ObjectData = BTreeMap<String, Property>;
#[derive(Clone)]
/// A Javascript property
pub struct Property {
/// If the type of this can be changed and this can be deleted
pub configurable : bool,
/// If the property shows up in enumeration of the object
pub enumerable: bool,
/// If this property can be changed with an assignment
pub writable: bool,
/// The value associated with the property
pub value: Value,
/// The function serving as getter
pub get: Value,
/// The function serving as setter
pub set: Value
}
impl Property {
/// Make a new property with the given value
pub fn new(value : Value) -> Property {
Property {
configurable: false,
enumerable: false,
writable: false,
value: value,
get: Value::undefined(),
set: Value::undefined()
}
}
}
impl ToValue for Property {
fn to_value(&self) -> Value {
let prop = Value::new_obj(None);
prop.set_field("configurable", to_value(self.configurable));
prop.set_field("enumerable", to_value(self.enumerable));
prop.set_field("writable", to_value(self.writable));
prop.set_field("value", self.value);
prop.set_field("get", self.get);
prop.set_field("set", self.set);
prop
}
}
impl FromValue for Property {
fn from_value(v:Value) -> Result<Property, &'static str> {
Ok(Property {
configurable: from_value(v.get_field("configurable")).unwrap(),
enumerable: from_value(v.get_field("enumerable")).unwrap(),
writable: from_value(v.get_field("writable")).unwrap(),
value: v.get_field("value"),
get: v.get_field("get"),
set: v.get_field("set")
})
}
}
/// Create a new object
pub fn make_object(_:Vec<Value>, _:Value, _:Value, _:Value) -> ResultValue {
Ok(Value::undefined())
}
/// Get the prototype of an object
pub fn get_proto_of(args:Vec<Value>, _:Value, _:Value, _:Value) -> ResultValue {
let obj = args[0];
Ok(obj.get_field(INSTANCE_PROTOTYPE))
}
/// Set the prototype of an object
pub fn set_proto_of(args:Vec<Value>, _:Value, _:Value, _:Value) -> ResultValue {
let obj = args[0];
let proto = args[1];
obj.set_field(INSTANCE_PROTOTYPE, proto);
Ok(obj)
}
/// Define a property in an object
pub fn define_prop(args:Vec<Value>, _:Value, _:Value, _:Value) -> ResultValue {
let obj = args[0];
let prop = from_value::<String>(args[1]).unwrap();
let desc = from_value::<Property>(args[2]).unwrap();
obj.set_prop(prop.as_slice(), desc);
Ok(Value::undefined())
}
/// To string
pub fn to_string(_:Vec<Value>, _:Value, _:Value, this:Value) -> ResultValue {
Ok(to_value(this.to_string()))
}
/// Check if it has a property
pub fn has_own_prop(args:Vec<Value>, _:Value, _:Value, this:Value) -> ResultValue {
let prop = if args.len() == 0 {
None
} else {
from_value::<String>(args[0]).ok()
};
Ok(to_value(prop.is_some() && this.get_prop(prop.unwrap().as_slice()).is_some()))
}
/// Create a new `Object` object
pub fn _create(global:Value) -> Value {
let object = Function::make(make_object, []);
let prototype = js!(global, {
"hasOwnProperty": Function::make(has_own_prop, ["property"]),
"toString": Function::make(to_string, [])
});
js_extend!(object, {
//TODO: Check that this works (commented) on compilation
//"length": i32,
"length": "Integer",
PROTOTYPE: prototype,
"setPrototypeOf": Function::make(get_proto_of, ["object", "prototype"]),
"getPrototypeOf": Function::make(get_proto_of, ["object"]),
"defineProperty": Function::make(define_prop, ["object", "property"])
});
object
}
/// Initialise the `Object` object on the global object
pub fn init(global:Value) {
js_extend!(global, {
"Object": _create(global)
});
}
|
use crate::utils::*;
pub(crate) const NAME: &[&str] = &["ExactSizeIterator"];
pub(crate) fn derive(data: &Data, items: &mut Vec<ItemImpl>) -> Result<()> {
#[cfg(not(feature = "exact_size_is_empty"))]
let is_empty = quote!();
#[cfg(feature = "exact_size_is_empty")]
let is_empty = quote! {
#[inline]
fn is_empty(&self) -> bool;
};
derive_trait!(
data,
Some(format_ident!("Item")),
parse_quote!(::core::iter::ExactSizeIterator)?,
parse_quote! {
trait ExactSizeIterator: ::core::iter::Iterator {
#[inline]
fn len(&self) -> usize;
#is_empty
}
}?,
)
.map(|item| items.push(item))
}
|
pub mod attribute;
pub mod classfile;
pub mod constant;
pub mod field;
pub mod method;
pub mod read;
|
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use rayon_array_add_benchmarks::*;
fn criterion_benchmark(c: &mut Criterion) {
{
let mut kib_array = c.benchmark_group("320 kib array");
let v1: &[u32] = &[1; 1024 * 10];
let mut v2 = vec![2; 1024 * 10];
kib_array.bench_function("seq_add_all", |b| {
b.iter(|| seq_add_all(black_box(&mut v2), black_box(&v1)))
});
kib_array.bench_function("par_add_all_par_iter", |b| {
b.iter(|| par_add_all_par_iter(black_box(&mut v2), black_box(&v1)))
});
kib_array.bench_function("par_add_all_join_1024_chunks", |b| {
b.iter(|| par_add_all_join(black_box(&mut v2), black_box(&v1), black_box(1024)))
});
}
{
let mut mib_array = c.benchmark_group("320 mib array");
mib_array.measurement_time(std::time::Duration::from_secs(60));
let v1: &[u32] = &[1; 1024 * 1024 * 10];
let mut v2 = vec![2; 1024 * 1024 * 10];
mib_array.bench_function("seq_add_all", |b| {
b.iter(|| seq_add_all(black_box(&mut v2), black_box(&v1)))
});
mib_array.bench_function("par_add_all_par_iter", |b| {
b.iter(|| par_add_all_par_iter(black_box(&mut v2), black_box(&v1)))
});
mib_array.bench_function("par_add_all_join_1024_chunks", |b| {
b.iter(|| par_add_all_join(black_box(&mut v2), black_box(&v1), black_box(1024)))
});
mib_array.bench_function("par_add_all_join_1048576_chunks", |b| {
b.iter(|| par_add_all_join(black_box(&mut v2), black_box(&v1), black_box(1024 * 1024)))
});
}
{
let mut gib_array = c.benchmark_group("gib array");
gib_array.sample_size(30);
gib_array.measurement_time(std::time::Duration::from_secs(60));
let v1: &[u32] = &[1; 1024 * 1024 * 32];
let mut v2 = vec![2; 1024 * 1024 * 32];
gib_array.bench_function("seq_add_all", |b| {
b.iter(|| seq_add_all(black_box(&mut v2), black_box(&v1)))
});
gib_array.bench_function("par_add_all_par_iter", |b| {
b.iter(|| par_add_all_par_iter(black_box(&mut v2), black_box(&v1)))
});
gib_array.bench_function("par_add_all_join_1024_chunks", |b| {
b.iter(|| par_add_all_join(black_box(&mut v2), black_box(&v1), black_box(1024)))
});
gib_array.bench_function("par_add_all_join_1048576_chunks", |b| {
b.iter(|| par_add_all_join(black_box(&mut v2), black_box(&v1), black_box(1024 * 1024)))
});
gib_array.bench_function("par_add_all_join_4194304_chunks", |b| {
b.iter(|| {
par_add_all_join(
black_box(&mut v2),
black_box(&v1),
black_box(1024 * 1024 * 4),
)
})
});
}
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
|
// Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use crate::{
blocks::BlockHeader,
proof_of_work::{blake_pow::blake_difficulty, monero_rx::monero_difficulty, Difficulty},
};
use bytes::{self, BufMut};
use serde::{Deserialize, Serialize};
use std::{
convert::TryFrom,
fmt::{Display, Error, Formatter},
};
use tari_crypto::tari_utilities::hex::Hex;
pub trait AchievedDifficulty {}
#[repr(u8)]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
pub enum PowAlgorithm {
Monero = 0,
Blake = 1,
}
/// Used to compare proof of work difficulties without scaling factors
#[derive(Debug, Clone, PartialEq)]
pub enum Ordering {
GreaterThan,
LessThan,
Equal,
Indeterminate,
}
impl TryFrom<u64> for PowAlgorithm {
type Error = String;
fn try_from(v: u64) -> Result<Self, Self::Error> {
match v {
0 => Ok(PowAlgorithm::Monero),
1 => Ok(PowAlgorithm::Blake),
_ => Err("Invalid PoWAlgorithm".into()),
}
}
}
/// The proof of work data structure that is included in the block header. There's some non-Rustlike redundancy here
/// to make serialization more straightforward
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ProofOfWork {
/// The total accumulated difficulty for each proof of work algorithms for all blocks since Genesis,
/// but not including this block, tracked separately.
pub accumulated_monero_difficulty: Difficulty,
pub accumulated_blake_difficulty: Difficulty,
/// The target difficulty for solving the current block using the specified proof of work algorithm.
pub target_difficulty: Difficulty,
/// The algorithm used to mine this block
pub pow_algo: PowAlgorithm,
/// Supplemental proof of work data. For example for Blake, this would be empty (only the block header is
/// required), but for Monero merge mining we need the Monero block header and RandomX seed hash.
pub pow_data: Vec<u8>,
}
impl Default for ProofOfWork {
fn default() -> Self {
Self {
accumulated_monero_difficulty: Difficulty::default(),
accumulated_blake_difficulty: Difficulty::default(),
target_difficulty: Difficulty::default(),
pow_algo: PowAlgorithm::Blake,
pow_data: vec![],
}
}
}
impl ProofOfWork {
/// Create a new `ProofOfWork` instance. Except for the algorithm used, the fields are uninitialized.
/// [achieved_difficulty] and [add_difficulty] can be used subsequently to properly populate the struct's fields.
pub fn new(pow_algo: PowAlgorithm) -> Self {
Self {
pow_algo,
accumulated_monero_difficulty: Difficulty::default(),
accumulated_blake_difficulty: Difficulty::default(),
target_difficulty: Difficulty::default(),
pow_data: vec![],
}
}
/// This function will calculate the achieved difficulty for the proof of work
/// given the block header.
/// This function is used to validate proofs of work generated by miners.
///
/// Generally speaking, the difficulty is roughly how many mining attempts a miner will make, _on average_ before
/// finding a nonce that meets the difficulty target.
///
/// In actuality, the difficulty is _defined_ as the maximum target value (u265) divided by the block header hash
/// (as a u256)
///
/// If there are any problems with calculating a difficulty (e.g. an invalid header), then the function returns a
/// difficulty of one.
pub fn achieved_difficulty(header: &BlockHeader) -> Difficulty {
match header.pow.pow_algo {
PowAlgorithm::Monero => monero_difficulty(header),
PowAlgorithm::Blake => blake_difficulty(header),
}
}
/// Calculates the total _ accumulated difficulty for the blockchain from the genesis block up until,
/// but _not including_ this block.
///
/// This uses a geometric mean to compare the two difficulties. See Issue #1075 (https://github.com/tari-project/tari/issues/1075) as to why this was done
///
/// The total accumulated difficulty is most often used to decide on which of two forks is the longest chain.
pub fn total_accumulated_difficulty(&self) -> Difficulty {
let d = (self.accumulated_monero_difficulty.as_u64() as f64 *
self.accumulated_blake_difficulty.as_u64() as f64)
.sqrt();
Difficulty::from(d.ceil() as u64)
}
/// Replaces the `next` proof of work's difficulty with the sum of this proof of work's total cumulative
/// difficulty and the provided `added_difficulty`.
pub fn add_difficulty(&mut self, prev: &ProofOfWork, added_difficulty: Difficulty) {
let pow = ProofOfWork::new_from_difficulty(prev, added_difficulty);
self.accumulated_blake_difficulty = pow.accumulated_blake_difficulty;
self.accumulated_monero_difficulty = pow.accumulated_monero_difficulty;
}
/// Creates a new proof of work from the provided proof of work difficulty with the sum of this proof of work's
/// total cumulative difficulty and the provided `added_difficulty`.
pub fn new_from_difficulty(pow: &ProofOfWork, added_difficulty: Difficulty) -> ProofOfWork {
let (m, b) = match pow.pow_algo {
PowAlgorithm::Monero => (
pow.accumulated_monero_difficulty + added_difficulty,
pow.accumulated_blake_difficulty,
),
PowAlgorithm::Blake => (
pow.accumulated_monero_difficulty,
pow.accumulated_blake_difficulty + added_difficulty,
),
};
ProofOfWork {
accumulated_monero_difficulty: m,
accumulated_blake_difficulty: b,
target_difficulty: pow.target_difficulty,
pow_algo: pow.pow_algo,
pow_data: pow.pow_data.clone(),
}
}
/// Compare the difficulties of this and another proof of work, without knowing anything about scaling factors.
/// Even without scaling factors, it is often possible to definitively order difficulties.
pub fn partial_cmp(&self, other: &ProofOfWork) -> Ordering {
if self.accumulated_blake_difficulty == other.accumulated_blake_difficulty &&
self.accumulated_monero_difficulty == other.accumulated_monero_difficulty
{
Ordering::Equal
} else if self.accumulated_blake_difficulty <= other.accumulated_blake_difficulty &&
self.accumulated_monero_difficulty <= other.accumulated_monero_difficulty
{
Ordering::LessThan
} else if self.accumulated_blake_difficulty >= other.accumulated_blake_difficulty &&
self.accumulated_monero_difficulty >= other.accumulated_monero_difficulty
{
Ordering::GreaterThan
} else {
Ordering::Indeterminate
}
}
/// Serialises the ProofOfWork instance into a byte string. Useful for feeding the PoW into a hash function.
pub fn to_bytes(&self) -> Vec<u8> {
let mut buf: Vec<u8> = Vec::with_capacity(256);
buf.put_u8(self.pow_algo as u8);
buf.put_u64_le(self.accumulated_monero_difficulty.as_u64());
buf.put_u64_le(self.accumulated_blake_difficulty.as_u64());
buf.put_slice(&self.pow_data);
buf
}
}
impl Display for PowAlgorithm {
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error> {
let algo = match self {
PowAlgorithm::Monero => "Monero",
PowAlgorithm::Blake => "Blake",
};
fmt.write_str(&algo.to_string())
}
}
impl Display for ProofOfWork {
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), Error> {
fmt.write_str(&format!(
"Mining algorithm: {}, \nTotal accumulated difficulty: \nMonero={}, Blake={}\nPow data: {}",
self.pow_algo,
self.accumulated_monero_difficulty,
self.accumulated_blake_difficulty,
self.pow_data.to_hex(),
))
}
}
#[cfg(test)]
mod test {
use crate::proof_of_work::{
proof_of_work::{Ordering, PowAlgorithm, ProofOfWork},
Difficulty,
};
#[test]
fn display() {
let pow = ProofOfWork::default();
assert_eq!(
&format!("{}", pow),
"Mining algorithm: Blake, \nTotal accumulated difficulty: \nMonero=1, Blake=1\nPow data: "
);
}
#[test]
fn to_bytes() {
let mut pow = ProofOfWork::default();
pow.accumulated_monero_difficulty = Difficulty::from(65);
pow.accumulated_blake_difficulty = Difficulty::from(257);
pow.pow_algo = PowAlgorithm::Blake;
assert_eq!(pow.to_bytes(), vec![1, 65, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0]);
}
#[test]
fn total_difficulty() {
let mut pow = ProofOfWork::default();
// Simple cases
pow.accumulated_monero_difficulty = 500.into();
pow.accumulated_blake_difficulty = 100.into();
assert_eq!(pow.total_accumulated_difficulty(), 224.into(), "Case 1");
pow.accumulated_monero_difficulty = 50.into();
pow.accumulated_blake_difficulty = 1000.into();
assert_eq!(pow.total_accumulated_difficulty(), 224.into(), "Case 2");
// Edge cases - Very large OOM difficulty differences
pow.accumulated_monero_difficulty = 444.into();
pow.accumulated_blake_difficulty = 1_555_222_888_555_555.into();
assert_eq!(pow.total_accumulated_difficulty(), 830_974_707.into(), "Case 3");
pow.accumulated_monero_difficulty = 1.into();
pow.accumulated_blake_difficulty = 15_222_333_444_555_666_777.into();
assert_eq!(pow.total_accumulated_difficulty(), 3_901_580_891.into(), "Case 4");
}
#[test]
fn add_difficulty() {
let mut pow = ProofOfWork::new(PowAlgorithm::Monero);
pow.accumulated_blake_difficulty = Difficulty::from(42);
pow.accumulated_monero_difficulty = Difficulty::from(420);
let mut pow2 = ProofOfWork::default();
pow2.add_difficulty(&pow, Difficulty::from(80));
assert_eq!(pow2.accumulated_blake_difficulty, Difficulty::from(42));
assert_eq!(pow2.accumulated_monero_difficulty, Difficulty::from(500));
}
#[test]
fn partial_cmp() {
let mut pow1 = ProofOfWork::default();
let mut pow2 = ProofOfWork::default();
// (0,0) vs (0,0)
assert_eq!(pow1.partial_cmp(&pow2), Ordering::Equal);
pow1.accumulated_monero_difficulty = 100.into();
// (100,0) vs (0,0)
assert_eq!(pow1.partial_cmp(&pow2), Ordering::GreaterThan);
pow2.accumulated_blake_difficulty = 50.into();
// (100,0) vs (0,50)
assert_eq!(pow1.partial_cmp(&pow2), Ordering::Indeterminate);
pow2.accumulated_monero_difficulty = 110.into();
// (100,0) vs (110, 50)
assert_eq!(pow1.partial_cmp(&pow2), Ordering::LessThan);
pow1.accumulated_blake_difficulty = 50.into();
// (100,50) vs (110, 50)
assert_eq!(pow1.partial_cmp(&pow2), Ordering::LessThan);
pow1.accumulated_monero_difficulty = 110.into();
// (110,50) vs (110, 50)
assert_eq!(pow1.partial_cmp(&pow2), Ordering::Equal);
pow1.accumulated_monero_difficulty = 200.into();
pow1.accumulated_blake_difficulty = 80.into();
// (200,80) vs (110, 50)
assert_eq!(pow1.partial_cmp(&pow2), Ordering::GreaterThan);
}
}
|
//! Contains device definitions and their parsing/creation functionality
mod controller;
mod device_info;
mod endpoints;
mod identifier;
mod protocol;
pub use crate::devices::controller::Controller;
use crate::devices::device_info::DeviceInfo;
use crate::devices::identifier::Identifier;
use libusb::{Context, Result};
/// Returns all controllers on USB that are supported by the package
pub fn find_supported_controllers(context: &Context) -> Result<Vec<Controller>> {
let devices = context.devices()?;
let mut controllers = Vec::new();
for device in devices.iter() {
let descriptor = device.device_descriptor()?;
let identifier = match Identifier::find_supported(&descriptor) {
Some(value) => value,
None => continue,
};
let handle = device.open()?;
let device_info = DeviceInfo::read(&handle, &descriptor)?;
let endpoints = endpoints::find(&device, &descriptor, &identifier.protocol)?;
controllers.push(Controller::new(identifier, device_info, handle, endpoints))
}
Ok(controllers)
}
|
use super::*;
struct ServerState {
model: Model,
events: std::collections::VecDeque<Event>,
next_event_index: usize,
first_event_index: usize,
clients_next_event: HashMap<Id, usize>,
}
impl ServerState {
fn new(model: Model) -> Self {
Self {
model,
events: default(),
next_event_index: 0,
first_event_index: 0,
clients_next_event: default(),
}
}
fn add_events(&mut self, events: impl IntoIterator<Item = Event>) {
for event in events.into_iter() {
// eprintln!("Add {}: {:?}", self.next_event_index, event);
self.events.push_back(event);
self.next_event_index += 1;
}
}
fn shrink(&mut self) {
let next_needed_event_index = self
.clients_next_event
.values()
.map(|&index| index)
.min()
.unwrap_or(self.next_event_index);
while self.first_event_index < next_needed_event_index {
self.events.pop_front();
self.first_event_index += 1;
}
}
fn get_new_events(&mut self, player_id: Id) -> Vec<Event> {
let next_event_index = self.clients_next_event[&player_id];
let mut result = Vec::new();
for index in next_event_index..self.next_event_index {
result.push(self.events[index - self.first_event_index].clone());
}
self.clients_next_event
.insert(player_id, self.next_event_index);
self.shrink();
// eprintln!("{:?}: {:?}", player_id, result);
result
}
}
struct Client {
player_id: Id,
server_state: Arc<Mutex<ServerState>>,
sender: Box<dyn geng::net::Sender<ServerMessage>>,
}
impl Drop for Client {
fn drop(&mut self) {
let mut server_state = self.server_state.lock().unwrap();
let events = server_state.model.drop_player(self.player_id);
server_state.add_events(events);
}
}
impl geng::net::Receiver<ClientMessage> for Client {
fn handle(&mut self, message: ClientMessage) {
let send_update = matches!(message, ClientMessage::Event(Event::PlayerUpdated(_)));
let mut server_state = self.server_state.lock().unwrap();
let events = server_state.model.handle_message(
self.player_id,
message,
// &mut *self.sender
);
server_state.add_events(events);
if send_update {
self.sender.send(ServerMessage::Update(
server_state.get_new_events(self.player_id),
));
}
}
}
struct ServerApp {
server_state: Arc<Mutex<ServerState>>,
}
impl geng::net::server::App for ServerApp {
type Client = Client;
type ServerMessage = ServerMessage;
type ClientMessage = ClientMessage;
fn connect(&mut self, mut sender: Box<dyn geng::net::Sender<ServerMessage>>) -> Client {
let mut server_state = self.server_state.lock().unwrap();
let (welcome, events) = server_state.model.welcome();
server_state.add_events(events);
let player_id = welcome.player_id;
sender.send(ServerMessage::Welcome(welcome));
let next_event_index = server_state.next_event_index;
server_state
.clients_next_event
.insert(player_id, next_event_index);
sender.send(ServerMessage::Update(vec![]));
Client {
server_state: self.server_state.clone(),
player_id,
sender,
}
}
}
pub struct Server {
server_state: Arc<Mutex<ServerState>>,
server: geng::net::Server<ServerApp>,
}
impl Server {
pub fn new<T: std::net::ToSocketAddrs + Debug + Copy>(addr: T, model: Model) -> Self {
let server_state = Arc::new(Mutex::new(ServerState::new(model)));
Self {
server_state: server_state.clone(),
server: geng::net::Server::new(
ServerApp {
server_state: server_state.clone(),
},
addr,
),
}
}
pub fn handle(&self) -> geng::net::ServerHandle {
self.server.handle()
}
pub fn run(self) {
let running = Arc::new(std::sync::atomic::AtomicBool::new(true));
let server_thread = std::thread::spawn({
let server_state = self.server_state;
let running = running.clone();
let mut sleep_time = 0;
move || {
while running.load(std::sync::atomic::Ordering::Relaxed) {
// TODO: smoother TPS
std::thread::sleep(std::time::Duration::from_millis(sleep_time));
let mut server_state = server_state.lock().unwrap();
let events = server_state.model.tick();
server_state.add_events(events);
sleep_time = (1000.0 / server_state.model.ticks_per_second) as u64;
}
}
});
self.server.run();
running.store(false, std::sync::atomic::Ordering::Relaxed);
server_thread.join().expect("Failed to join server thread");
}
}
// pub struct Server {
// handle: geng::net::ServerHandle,
// thread: Option<std::thread::JoinHandle<()>>,
// }
// impl Server {
// pub fn new() -> Self {
// let server = ServerState::new(SERVER_ADDR, Model::new());
// let handle = server.handle();
// let thread = std::thread::spawn(move || server.run());
// Self {
// handle,
// thread: Some(thread),
// }
// }
// }
// impl Drop for Server {
// fn drop(&mut self) {
// self.handle.shutdown();
// self.thread
// .take()
// .unwrap()
// .join()
// .expect("Failed to join server thread");
// }
// }
|
use log::error;
use warp::ws::Message;
use std::time::SystemTime;
use crate::database as db;
use serde::{Serialize, Deserialize};
use deadpool_postgres::{Pool, PoolError};
use super::upgrade::{ConnID, Sender, Group, Groups, UserGroups};
#[derive(Deserialize)]
#[serde(tag="type")]
#[serde(rename_all="snake_case")]
enum ClientMessage {
CreateMessage { content: String, channel_id: db::ChannelID },
RequestRecentMessages { channel_id: db::ChannelID },
RequestOldMessages { channel_id: db::ChannelID, message_id: db::MessageID },
CreateChannel { name: String },
RequestChannels,
DeleteChannel { channel_id: db::ChannelID },
RenameChannel { channel_id: db::ChannelID, name: String },
RequestUsers,
RenameGroup { name: String, picture: String },
}
#[derive(Serialize)]
struct RecentMessage {
message_id: db::MessageID,
timestamp: u64,
author: db::UserID,
content: String,
channel_id: db::ChannelID,
}
#[derive(Serialize)]
struct GenericRecentMessage {
message_id: db::MessageID,
timestamp: u64,
author: db::UserID,
content: String,
}
#[derive(Serialize)]
#[serde(rename_all="snake_case")]
enum UserStatus {
Online,
Offline,
}
#[derive(Serialize)]
struct User {
user_id: db::UserID,
name: String,
picture: String,
status: UserStatus,
}
#[derive(Serialize)]
#[serde(rename_all="snake_case")]
enum ErrorCategory {
Application,
Request,
ChannelCreate,
ChannelRename,
ChannelDelete,
GroupRename,
}
use ErrorCategory::*;
#[derive(Serialize)]
#[serde(rename_all="snake_case")]
enum ErrorCode {
Json,
Database,
ChannelIdInvalid,
MessageInvalid,
NameInvalid,
NameExists,
LoneChannel,
PictureInvalid,
}
use ErrorCode::*;
#[derive(Serialize)]
#[serde(tag="type")]
#[serde(rename_all="snake_case")]
enum ServerMessage<'a> {
Error { category: ErrorCategory, code: ErrorCode },
MessageReceipt { message_id: db::MessageID, timestamp: u64, channel_id: db::ChannelID },
RecentMessage(RecentMessage),
RecentMessageList { channel_id: db::ChannelID, messages: Vec<GenericRecentMessage> },
OldMessageList { channel_id: db::ChannelID, messages: Vec<GenericRecentMessage> },
ChannelCreated { channel_id: db::ChannelID, name: &'a String },
ChannelList { channels: &'a Vec<db::Channel> },
ChannelDeleted { channel_id: db::ChannelID },
ChannelRenamed { channel_id: db::ChannelID, name: &'a String },
UserList { users: Vec<User> },
UserStatusChanged { user_id: db::UserID, status: UserStatus },
UserRenamed { user_id: db::UserID, name: &'a String, picture: &'a String },
UserDeleted { user_id: db::UserID },
GroupRenamed { group_id: db::GroupID, name: String, picture: String },
GroupDeleted { group_id: db::GroupID },
}
fn as_timestamp(time: SystemTime) -> u64 {
time.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs()
}
fn send_message(ch_tx: &Sender, message: String) {
if ch_tx.send(Ok(Message::text(message))).is_err() {
// the connection handler will handle the possible error
}
}
impl Group {
fn find_channel(&self, channel_id: db::ChannelID) -> usize {
match self.channels.binary_search_by(|ch| ch.channel_id.cmp(&channel_id)) {
Ok(i) => i,
Err(_) => usize::MAX
}
}
fn contains_channel(&self, channel_id: db::ChannelID) -> bool {
self.find_channel(channel_id) != usize::MAX
}
/// Send a message to all connections.
fn send_all(&self, message: ServerMessage) {
let response = serde_json::to_string(&message).unwrap();
for (_, ch_tx) in self.connections.iter() {
send_message(ch_tx, response.clone());
}
}
/// Send a peer message to all connections but the current connection.
/// Send a reply message to the current connection.
fn send_peer_reply(&self, conn_id: ConnID, peer: ServerMessage, reply: ServerMessage) {
let peer_response = serde_json::to_string(&peer).unwrap();
let reply_response = serde_json::to_string(&reply).unwrap();
for (&other_conn_id, ch_tx) in self.connections.iter() {
if other_conn_id == conn_id {
send_message(ch_tx, reply_response.clone());
} else {
send_message(ch_tx, peer_response.clone());
}
}
}
/// Send a reply message to the current connection.
fn send_reply(&self, conn_id: ConnID, message: ServerMessage) {
let sender = &self.connections[&conn_id];
send_message(sender, serde_json::to_string(&message).unwrap());
}
/// Send a reply error to the current connection
fn send_reply_error(&self, conn_id: ConnID, category: ErrorCategory, code: ErrorCode) {
self.send_reply(conn_id, ServerMessage::Error {
category, code
});
}
fn send_user_status(&self, user_id: db::UserID, status: UserStatus) {
self.send_all(ServerMessage::UserStatusChanged {
user_id,
status,
});
}
pub fn send_user_online(&self, user_id: db::UserID) {
self.send_user_status(user_id, UserStatus::Online);
}
pub fn send_user_offline(&self, user_id: db::UserID) {
self.send_user_status(user_id, UserStatus::Offline);
}
pub fn send_user_renamed(&self, user_id: db::UserID, name: &String, picture: &String) {
self.send_all(ServerMessage::UserRenamed {
user_id,
name,
picture,
})
}
pub fn kick_user(&self, user_id: db::UserID) {
let message = Message::close_with(4000u16, "kick");
for conn_id in self.online_users[&user_id].iter() {
if self.connections[conn_id].send(Ok(message.clone())).is_err() {}
}
}
pub fn send_delete_group(&self, user_id: db::UserID, group_id: db::GroupID) {
let message = serde_json::to_string(&ServerMessage::GroupDeleted {
group_id
}).unwrap();
for conn_id in self.online_users[&user_id].iter() {
send_message(&self.connections[conn_id], message.clone());
}
}
pub fn send_delete_user(&self, user_id: db::UserID) {
self.send_all(ServerMessage::UserDeleted { user_id });
}
}
pub struct MessageContext<'a> {
pub user_id: db::UserID,
pub group_id: db::GroupID,
pub conn_id: ConnID,
pub groups: &'a Groups,
pub user_groups: &'a UserGroups,
pub pool: &'a Pool,
}
impl<'a> MessageContext<'a> {
pub async fn handle(&self, message: Message) {
let message = match message.to_str() {
Ok(m) => m,
Err(_) => return,
};
let client_message = match serde_json::from_str::<ClientMessage>(message) {
Ok(m) => m,
Err(e) => {
error!("{}", e);
let group = &self.groups.read().await[&self.group_id];
group.send_reply_error(self.conn_id, Request, Json);
return;
}
};
let result = match client_message {
ClientMessage::CreateMessage { content, channel_id } =>
self.create_message(content, channel_id).await,
ClientMessage::RequestRecentMessages { channel_id } =>
self.request_recent_messages(channel_id).await,
ClientMessage::RequestOldMessages { channel_id, message_id } =>
self.request_old_messages(channel_id, message_id).await,
ClientMessage::CreateChannel { name } =>
self.create_channel(name).await,
ClientMessage::RequestChannels =>
self.request_channels().await,
ClientMessage::DeleteChannel { channel_id } =>
self.delete_channel(channel_id).await,
ClientMessage::RequestUsers =>
self.request_users().await,
ClientMessage::RenameChannel { channel_id, name } =>
self.rename_channel(channel_id, name).await,
ClientMessage::RenameGroup { name, picture } =>
self.rename_group(name, picture).await,
};
if let Err(e) = result {
error!("{}", e);
let group = &self.groups.read().await[&self.group_id];
group.send_reply_error(self.conn_id, Application, Database);
}
}
async fn create_message(&self, content: String, channel_id: db::ChannelID)
-> Result<(), PoolError>
{
let time = SystemTime::now();
let timestamp = as_timestamp(time);
let groups_guard = self.groups.read().await;
let group = &groups_guard[&self.group_id];
if !db::valid_message(&content) {
group.send_reply_error(self.conn_id, Request, MessageInvalid);
return Ok(());
}
if !group.contains_channel(channel_id) {
group.send_reply_error(self.conn_id, Request, ChannelIdInvalid);
return Ok(());
}
let message_id = db::create_message(self.pool.clone(), time, self.user_id, &content, channel_id).await?;
let peer = ServerMessage::RecentMessage(RecentMessage {
message_id,
timestamp,
author: self.user_id,
content,
channel_id,
});
let echo = ServerMessage::MessageReceipt {
message_id,
timestamp,
channel_id,
};
group.send_peer_reply(self.conn_id, peer, echo);
Ok(())
}
async fn request_recent_messages(&self, channel_id: db::ChannelID)
-> Result<(), PoolError>
{
let groups_guard = self.groups.read().await;
let group = &groups_guard[&self.group_id];
if !group.contains_channel(channel_id) {
group.send_reply_error(self.conn_id, Request, ChannelIdInvalid);
return Ok(());
}
let rows = db::recent_messages(self.pool.clone(), channel_id).await?;
group.send_reply(self.conn_id, ServerMessage::RecentMessageList {
channel_id,
messages: rows.iter()
.map(|row| GenericRecentMessage {
message_id: row.get(0),
timestamp: as_timestamp(row.get(1)),
author: row.get(2),
content: row.get(3)
})
.collect()
});
Ok(())
}
async fn request_old_messages(&self, channel_id: db::ChannelID, message_id: db::MessageID)
-> Result<(), PoolError>
{
let groups_guard = self.groups.read().await;
let group = &groups_guard[&self.group_id];
if !group.contains_channel(channel_id) {
group.send_reply_error(self.conn_id, Request, ChannelIdInvalid);
return Ok(());
}
let rows = db::old_messages(self.pool.clone(), channel_id, message_id).await?;
group.send_reply(self.conn_id, ServerMessage::OldMessageList {
channel_id,
messages: rows.iter()
.map(|row| GenericRecentMessage {
message_id: row.get(0),
timestamp: as_timestamp(row.get(1)),
author: row.get(2),
content: row.get(3)
})
.collect()
});
Ok(())
}
async fn create_channel(&self, name: String) -> Result<(), PoolError> {
let mut groups_guard = self.groups.write().await;
let group = &mut groups_guard.get_mut(&self.group_id).unwrap();
if !db::valid_channel_name(&name) {
// This shouldn't happen unless someone is bypassing the JavaScript
// validation.
group.send_reply_error(self.conn_id, ChannelCreate, NameInvalid);
return Ok(());
}
let channel_id = match db::create_channel(self.pool.clone(), self.group_id, &name).await? {
Some(id) => id,
None => {
group.send_reply_error(self.conn_id, ChannelCreate, NameExists);
return Ok(());
}
};
group.send_all(ServerMessage::ChannelCreated {
channel_id,
name: &name,
});
group.channels.push(db::Channel {
channel_id,
name
});
Ok(())
}
async fn request_channels(&self) -> Result<(), PoolError> {
let groups_guard = self.groups.read().await;
let group = &groups_guard[&self.group_id];
group.send_reply(self.conn_id, ServerMessage::ChannelList {
channels: &group.channels
});
Ok(())
}
async fn delete_channel(&self, channel_id: db::ChannelID) -> Result<(), PoolError> {
let mut groups_guard = self.groups.write().await;
let group = &mut groups_guard.get_mut(&self.group_id).unwrap();
if group.channels.len() == 1 {
group.send_reply_error(self.conn_id, ChannelDelete, LoneChannel);
return Ok(());
}
let channel_index = group.find_channel(channel_id);
if channel_index == usize::MAX {
group.send_reply_error(self.conn_id, Request, ChannelIdInvalid);
return Ok(());
}
if !db::delete_channel(self.pool.clone(), channel_id).await? {
// If the above checks pass then this cannot happen
group.send_reply_error(self.conn_id, Request, ChannelIdInvalid);
return Ok(());
}
group.channels.remove(channel_index);
group.send_all(ServerMessage::ChannelDeleted {
channel_id
});
Ok(())
}
async fn request_users(&self) -> Result<(), PoolError> {
let groups_guard = self.groups.read().await;
let group = &groups_guard[&self.group_id];
let group_users = db::group_users(self.pool.clone(), self.group_id).await?;
let mut users = Vec::new();
for user in group_users.iter() {
let status = if group.online_users.contains_key(&user.user_id) {
UserStatus::Online
} else {
UserStatus::Offline
};
users.push(User {
user_id: user.user_id,
name: user.name.clone(),
picture: user.picture.clone(),
status
});
}
group.send_reply(self.conn_id, ServerMessage::UserList {
users
});
Ok(())
}
async fn rename_channel(&self, channel_id: db::ChannelID, name: String) -> Result<(), PoolError> {
let mut groups_guard = self.groups.write().await;
let group = &mut groups_guard.get_mut(&self.group_id).unwrap();
if !db::valid_channel_name(&name) {
// This shouldn't happen unless someone is bypassing the JavaScript
// validation.
group.send_reply_error(self.conn_id, ChannelRename, NameInvalid);
return Ok(());
}
let channel_index = group.find_channel(channel_id);
if channel_index == usize::MAX {
group.send_reply_error(self.conn_id, Request, ChannelIdInvalid);
return Ok(());
}
if !db::rename_channel(self.pool.clone(), self.group_id, channel_id, &name).await? {
group.send_reply_error(self.conn_id, ChannelRename, NameExists);
return Ok(());
}
group.send_all(ServerMessage::ChannelRenamed {
channel_id,
name: &name,
});
group.channels[channel_index].name = name;
Ok(())
}
async fn rename_group(&self, name: String, picture: String) -> Result<(), PoolError> {
let groups_guard = self.groups.read().await;
let group = &groups_guard[&self.group_id];
if !db::valid_group_name(&name) {
group.send_reply_error(self.conn_id, GroupRename, NameInvalid);
return Ok(());
}
if !db::valid_url(&picture) {
group.send_reply_error(self.conn_id, GroupRename, PictureInvalid);
return Ok(());
}
if !db::rename_group(self.pool.clone(), self.group_id, &name, &picture).await? {
group.send_reply_error(self.conn_id, GroupRename, NameExists);
return Ok(());
}
let users = db::group_user_ids(self.pool.clone(), self.group_id).await?;
let message = serde_json::to_string(&ServerMessage::GroupRenamed {
group_id: self.group_id,
name,
picture
}).unwrap();
// Need to send this to all users that are members of the group.
// They may be logged into another group.
let user_groups_guard = self.user_groups.read().await;
for user_id in users.iter() {
if let Some(groups) = user_groups_guard.get(&user_id) {
for group_id in groups.iter() {
let group = &groups_guard[group_id];
for conn_id in group.online_users[&user_id].iter() {
send_message(&group.connections[conn_id], message.clone());
}
}
}
}
Ok(())
}
}
|
use itertools::Itertools;
use regex::Regex;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs;
use std::lazy::SyncLazy;
use std::path::Path;
use walkdir::WalkDir;
use crate::clippy_project_root;
const GENERATED_FILE_COMMENT: &str = "// This file was generated by `cargo dev update_lints`.\n\
// Use that command to update this file and do not edit by hand.\n\
// Manual edits will be overwritten.\n\n";
static DEC_CLIPPY_LINT_RE: SyncLazy<Regex> = SyncLazy::new(|| {
Regex::new(
r#"(?x)
declare_clippy_lint!\s*[\{(]
(?:\s+///.*)*
(?:\s*\#\[clippy::version\s*=\s*"[^"]*"\])?
\s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
(?P<cat>[a-z_]+)\s*,\s*
"(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
"#,
)
.unwrap()
});
static DEC_DEPRECATED_LINT_RE: SyncLazy<Regex> = SyncLazy::new(|| {
Regex::new(
r#"(?x)
declare_deprecated_lint!\s*[{(]\s*
(?:\s+///.*)*
(?:\s*\#\[clippy::version\s*=\s*"[^"]*"\])?
\s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
"(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
"#,
)
.unwrap()
});
static NL_ESCAPE_RE: SyncLazy<Regex> = SyncLazy::new(|| Regex::new(r#"\\\n\s*"#).unwrap());
static DOCS_LINK: &str = "https://rust-lang.github.io/rust-clippy/master/index.html";
#[derive(Clone, Copy, PartialEq)]
pub enum UpdateMode {
Check,
Change,
}
/// Runs the `update_lints` command.
///
/// This updates various generated values from the lint source code.
///
/// `update_mode` indicates if the files should be updated or if updates should be checked for.
///
/// # Panics
///
/// Panics if a file path could not read from or then written to
#[allow(clippy::too_many_lines)]
pub fn run(update_mode: UpdateMode) {
let lint_list: Vec<Lint> = gather_all().collect();
let internal_lints = Lint::internal_lints(&lint_list);
let deprecated_lints = Lint::deprecated_lints(&lint_list);
let usable_lints = Lint::usable_lints(&lint_list);
let mut sorted_usable_lints = usable_lints.clone();
sorted_usable_lints.sort_by_key(|lint| lint.name.clone());
let usable_lint_count = round_to_fifty(usable_lints.len());
let mut file_change = false;
file_change |= replace_region_in_file(
Path::new("README.md"),
&format!(
r#"\[There are over \d+ lints included in this crate!\]\({}\)"#,
DOCS_LINK
),
"",
true,
update_mode == UpdateMode::Change,
|| {
vec",
usable_lint_count, DOCS_LINK
)]
},
)
.changed;
file_change |= replace_region_in_file(
Path::new("CHANGELOG.md"),
"<!-- begin autogenerated links to lint list -->",
"<!-- end autogenerated links to lint list -->",
false,
update_mode == UpdateMode::Change,
|| gen_changelog_lint_list(usable_lints.iter().chain(deprecated_lints.iter())),
)
.changed;
// This has to be in lib.rs, otherwise rustfmt doesn't work
file_change |= replace_region_in_file(
Path::new("clippy_lints/src/lib.rs"),
"begin lints modules",
"end lints modules",
false,
update_mode == UpdateMode::Change,
|| gen_modules_list(usable_lints.iter()),
)
.changed;
if file_change && update_mode == UpdateMode::Check {
exit_with_failure();
}
process_file(
"clippy_lints/src/lib.register_lints.rs",
update_mode,
&gen_register_lint_list(internal_lints.iter(), usable_lints.iter()),
);
process_file(
"clippy_lints/src/lib.deprecated.rs",
update_mode,
&gen_deprecated(deprecated_lints.iter()),
);
let all_group_lints = usable_lints.iter().filter(|l| {
matches!(
&*l.group,
"correctness" | "suspicious" | "style" | "complexity" | "perf"
)
});
let content = gen_lint_group_list("all", all_group_lints);
process_file("clippy_lints/src/lib.register_all.rs", update_mode, &content);
for (lint_group, lints) in Lint::by_lint_group(usable_lints.into_iter().chain(internal_lints)) {
let content = gen_lint_group_list(&lint_group, lints.iter());
process_file(
&format!("clippy_lints/src/lib.register_{}.rs", lint_group),
update_mode,
&content,
);
}
}
pub fn print_lints() {
let lint_list: Vec<Lint> = gather_all().collect();
let usable_lints = Lint::usable_lints(&lint_list);
let usable_lint_count = usable_lints.len();
let grouped_by_lint_group = Lint::by_lint_group(usable_lints.into_iter());
for (lint_group, mut lints) in grouped_by_lint_group {
if lint_group == "Deprecated" {
continue;
}
println!("\n## {}", lint_group);
lints.sort_by_key(|l| l.name.clone());
for lint in lints {
println!("* [{}]({}#{}) ({})", lint.name, DOCS_LINK, lint.name, lint.desc);
}
}
println!("there are {} lints", usable_lint_count);
}
fn round_to_fifty(count: usize) -> usize {
count / 50 * 50
}
fn process_file(path: impl AsRef<Path>, update_mode: UpdateMode, content: &str) {
if update_mode == UpdateMode::Check {
let old_content =
fs::read_to_string(&path).unwrap_or_else(|e| panic!("Cannot read from {}: {}", path.as_ref().display(), e));
if content != old_content {
exit_with_failure();
}
} else {
fs::write(&path, content.as_bytes())
.unwrap_or_else(|e| panic!("Cannot write to {}: {}", path.as_ref().display(), e));
}
}
fn exit_with_failure() {
println!(
"Not all lints defined properly. \
Please run `cargo dev update_lints` to make sure all lints are defined properly."
);
std::process::exit(1);
}
/// Lint data parsed from the Clippy source code.
#[derive(Clone, PartialEq, Debug)]
struct Lint {
name: String,
group: String,
desc: String,
deprecation: Option<String>,
module: String,
}
impl Lint {
#[must_use]
fn new(name: &str, group: &str, desc: &str, deprecation: Option<&str>, module: &str) -> Self {
Self {
name: name.to_lowercase(),
group: group.to_string(),
desc: NL_ESCAPE_RE.replace(&desc.replace("\\\"", "\""), "").to_string(),
deprecation: deprecation.map(ToString::to_string),
module: module.to_string(),
}
}
/// Returns all non-deprecated lints and non-internal lints
#[must_use]
fn usable_lints(lints: &[Self]) -> Vec<Self> {
lints
.iter()
.filter(|l| l.deprecation.is_none() && !l.group.starts_with("internal"))
.cloned()
.collect()
}
/// Returns all internal lints (not `internal_warn` lints)
#[must_use]
fn internal_lints(lints: &[Self]) -> Vec<Self> {
lints.iter().filter(|l| l.group == "internal").cloned().collect()
}
/// Returns all deprecated lints
#[must_use]
fn deprecated_lints(lints: &[Self]) -> Vec<Self> {
lints.iter().filter(|l| l.deprecation.is_some()).cloned().collect()
}
/// Returns the lints in a `HashMap`, grouped by the different lint groups
#[must_use]
fn by_lint_group(lints: impl Iterator<Item = Self>) -> HashMap<String, Vec<Self>> {
lints.map(|lint| (lint.group.to_string(), lint)).into_group_map()
}
}
/// Generates the code for registering a group
fn gen_lint_group_list<'a>(group_name: &str, lints: impl Iterator<Item = &'a Lint>) -> String {
let mut details: Vec<_> = lints.map(|l| (&l.module, l.name.to_uppercase())).collect();
details.sort_unstable();
let mut output = GENERATED_FILE_COMMENT.to_string();
output.push_str(&format!(
"store.register_group(true, \"clippy::{0}\", Some(\"clippy_{0}\"), vec![\n",
group_name
));
for (module, name) in details {
output.push_str(&format!(" LintId::of({}::{}),\n", module, name));
}
output.push_str("])\n");
output
}
/// Generates the module declarations for `lints`
#[must_use]
fn gen_modules_list<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
lints
.map(|l| &l.module)
.unique()
.map(|module| format!("mod {};", module))
.sorted()
.collect::<Vec<String>>()
}
/// Generates the list of lint links at the bottom of the CHANGELOG
#[must_use]
fn gen_changelog_lint_list<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
lints
.sorted_by_key(|l| &l.name)
.map(|l| format!("[`{}`]: {}#{}", l.name, DOCS_LINK, l.name))
.collect()
}
/// Generates the `register_removed` code
#[must_use]
fn gen_deprecated<'a>(lints: impl Iterator<Item = &'a Lint>) -> String {
let mut output = GENERATED_FILE_COMMENT.to_string();
output.push_str("{\n");
for Lint { name, deprecation, .. } in lints {
output.push_str(&format!(
concat!(
" store.register_removed(\n",
" \"clippy::{}\",\n",
" \"{}\",\n",
" );\n"
),
name,
deprecation.as_ref().expect("`lints` are deprecated")
));
}
output.push_str("}\n");
output
}
/// Generates the code for registering lints
#[must_use]
fn gen_register_lint_list<'a>(
internal_lints: impl Iterator<Item = &'a Lint>,
usable_lints: impl Iterator<Item = &'a Lint>,
) -> String {
let mut details: Vec<_> = internal_lints
.map(|l| (false, &l.module, l.name.to_uppercase()))
.chain(usable_lints.map(|l| (true, &l.module, l.name.to_uppercase())))
.collect();
details.sort_unstable();
let mut output = GENERATED_FILE_COMMENT.to_string();
output.push_str("store.register_lints(&[\n");
for (is_public, module_name, lint_name) in details {
if !is_public {
output.push_str(" #[cfg(feature = \"internal-lints\")]\n");
}
output.push_str(&format!(" {}::{},\n", module_name, lint_name));
}
output.push_str("])\n");
output
}
/// Gathers all files in `src/clippy_lints` and gathers all lints inside
fn gather_all() -> impl Iterator<Item = Lint> {
lint_files().flat_map(|f| gather_from_file(&f))
}
fn gather_from_file(dir_entry: &walkdir::DirEntry) -> impl Iterator<Item = Lint> {
let content = fs::read_to_string(dir_entry.path()).unwrap();
let path = dir_entry.path();
let filename = path.file_stem().unwrap();
let path_buf = path.with_file_name(filename);
let mut rel_path = path_buf
.strip_prefix(clippy_project_root().join("clippy_lints/src"))
.expect("only files in `clippy_lints/src` should be looked at");
// If the lints are stored in mod.rs, we get the module name from
// the containing directory:
if filename == "mod" {
rel_path = rel_path.parent().unwrap();
}
let module = rel_path
.components()
.map(|c| c.as_os_str().to_str().unwrap())
.collect::<Vec<_>>()
.join("::");
parse_contents(&content, &module)
}
fn parse_contents(content: &str, module: &str) -> impl Iterator<Item = Lint> {
let lints = DEC_CLIPPY_LINT_RE
.captures_iter(content)
.map(|m| Lint::new(&m["name"], &m["cat"], &m["desc"], None, module));
let deprecated = DEC_DEPRECATED_LINT_RE
.captures_iter(content)
.map(|m| Lint::new(&m["name"], "Deprecated", &m["desc"], Some(&m["desc"]), module));
// Removing the `.collect::<Vec<Lint>>().into_iter()` causes some lifetime issues due to the map
lints.chain(deprecated).collect::<Vec<Lint>>().into_iter()
}
/// Collects all .rs files in the `clippy_lints/src` directory
fn lint_files() -> impl Iterator<Item = walkdir::DirEntry> {
// We use `WalkDir` instead of `fs::read_dir` here in order to recurse into subdirectories.
// Otherwise we would not collect all the lints, for example in `clippy_lints/src/methods/`.
let path = clippy_project_root().join("clippy_lints/src");
WalkDir::new(path)
.into_iter()
.filter_map(Result::ok)
.filter(|f| f.path().extension() == Some(OsStr::new("rs")))
}
/// Whether a file has had its text changed or not
#[derive(PartialEq, Debug)]
struct FileChange {
changed: bool,
new_lines: String,
}
/// Replaces a region in a file delimited by two lines matching regexes.
///
/// `path` is the relative path to the file on which you want to perform the replacement.
///
/// See `replace_region_in_text` for documentation of the other options.
///
/// # Panics
///
/// Panics if the path could not read or then written
fn replace_region_in_file<F>(
path: &Path,
start: &str,
end: &str,
replace_start: bool,
write_back: bool,
replacements: F,
) -> FileChange
where
F: FnOnce() -> Vec<String>,
{
let contents = fs::read_to_string(path).unwrap_or_else(|e| panic!("Cannot read from {}: {}", path.display(), e));
let file_change = replace_region_in_text(&contents, start, end, replace_start, replacements);
if write_back {
if let Err(e) = fs::write(path, file_change.new_lines.as_bytes()) {
panic!("Cannot write to {}: {}", path.display(), e);
}
}
file_change
}
/// Replaces a region in a text delimited by two lines matching regexes.
///
/// * `text` is the input text on which you want to perform the replacement
/// * `start` is a `&str` that describes the delimiter line before the region you want to replace.
/// As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
/// * `end` is a `&str` that describes the delimiter line until where the replacement should happen.
/// As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
/// * If `replace_start` is true, the `start` delimiter line is replaced as well. The `end`
/// delimiter line is never replaced.
/// * `replacements` is a closure that has to return a `Vec<String>` which contains the new text.
///
/// If you want to perform the replacement on files instead of already parsed text,
/// use `replace_region_in_file`.
///
/// # Example
///
/// ```ignore
/// let the_text = "replace_start\nsome text\nthat will be replaced\nreplace_end";
/// let result =
/// replace_region_in_text(the_text, "replace_start", "replace_end", false, || {
/// vec!["a different".to_string(), "text".to_string()]
/// })
/// .new_lines;
/// assert_eq!("replace_start\na different\ntext\nreplace_end", result);
/// ```
///
/// # Panics
///
/// Panics if start or end is not valid regex
fn replace_region_in_text<F>(text: &str, start: &str, end: &str, replace_start: bool, replacements: F) -> FileChange
where
F: FnOnce() -> Vec<String>,
{
let replace_it = replacements();
let mut in_old_region = false;
let mut found = false;
let mut new_lines = vec![];
let start = Regex::new(start).unwrap();
let end = Regex::new(end).unwrap();
for line in text.lines() {
if in_old_region {
if end.is_match(line) {
in_old_region = false;
new_lines.extend(replace_it.clone());
new_lines.push(line.to_string());
}
} else if start.is_match(line) {
if !replace_start {
new_lines.push(line.to_string());
}
in_old_region = true;
found = true;
} else {
new_lines.push(line.to_string());
}
}
if !found {
// This happens if the provided regex in `clippy_dev/src/main.rs` does not match in the
// given text or file. Most likely this is an error on the programmer's side and the Regex
// is incorrect.
eprintln!("error: regex \n{:?}\ndoesn't match. You may have to update it.", start);
std::process::exit(1);
}
let mut new_lines = new_lines.join("\n");
if text.ends_with('\n') {
new_lines.push('\n');
}
let changed = new_lines != text;
FileChange { changed, new_lines }
}
#[test]
fn test_parse_contents() {
let result: Vec<Lint> = parse_contents(
r#"
declare_clippy_lint! {
#[clippy::version = "Hello Clippy!"]
pub PTR_ARG,
style,
"really long \
text"
}
declare_clippy_lint!{
#[clippy::version = "Test version"]
pub DOC_MARKDOWN,
pedantic,
"single line"
}
/// some doc comment
declare_deprecated_lint! {
#[clippy::version = "I'm a version"]
pub SHOULD_ASSERT_EQ,
"`assert!()` will be more flexible with RFC 2011"
}
"#,
"module_name",
)
.collect();
let expected = vec![
Lint::new("ptr_arg", "style", "really long text", None, "module_name"),
Lint::new("doc_markdown", "pedantic", "single line", None, "module_name"),
Lint::new(
"should_assert_eq",
"Deprecated",
"`assert!()` will be more flexible with RFC 2011",
Some("`assert!()` will be more flexible with RFC 2011"),
"module_name",
),
];
assert_eq!(expected, result);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_replace_region() {
let text = "\nabc\n123\n789\ndef\nghi";
let expected = FileChange {
changed: true,
new_lines: "\nabc\nhello world\ndef\nghi".to_string(),
};
let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, false, || {
vec!["hello world".to_string()]
});
assert_eq!(expected, result);
}
#[test]
fn test_replace_region_with_start() {
let text = "\nabc\n123\n789\ndef\nghi";
let expected = FileChange {
changed: true,
new_lines: "\nhello world\ndef\nghi".to_string(),
};
let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, true, || {
vec!["hello world".to_string()]
});
assert_eq!(expected, result);
}
#[test]
fn test_replace_region_no_changes() {
let text = "123\n456\n789";
let expected = FileChange {
changed: false,
new_lines: "123\n456\n789".to_string(),
};
let result = replace_region_in_text(text, r#"^\s*123$"#, r#"^\s*456"#, false, Vec::new);
assert_eq!(expected, result);
}
#[test]
fn test_usable_lints() {
let lints = vec![
Lint::new("should_assert_eq", "Deprecated", "abc", Some("Reason"), "module_name"),
Lint::new("should_assert_eq2", "Not Deprecated", "abc", None, "module_name"),
Lint::new("should_assert_eq2", "internal", "abc", None, "module_name"),
Lint::new("should_assert_eq2", "internal_style", "abc", None, "module_name"),
];
let expected = vec![Lint::new(
"should_assert_eq2",
"Not Deprecated",
"abc",
None,
"module_name",
)];
assert_eq!(expected, Lint::usable_lints(&lints));
}
#[test]
fn test_by_lint_group() {
let lints = vec![
Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
];
let mut expected: HashMap<String, Vec<Lint>> = HashMap::new();
expected.insert(
"group1".to_string(),
vec![
Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
],
);
expected.insert(
"group2".to_string(),
vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")],
);
assert_eq!(expected, Lint::by_lint_group(lints.into_iter()));
}
#[test]
fn test_gen_changelog_lint_list() {
let lints = vec![
Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
];
let expected = vec![
format!("[`should_assert_eq`]: {}#should_assert_eq", DOCS_LINK),
format!("[`should_assert_eq2`]: {}#should_assert_eq2", DOCS_LINK),
];
assert_eq!(expected, gen_changelog_lint_list(lints.iter()));
}
#[test]
fn test_gen_deprecated() {
let lints = vec![
Lint::new(
"should_assert_eq",
"group1",
"abc",
Some("has been superseded by should_assert_eq2"),
"module_name",
),
Lint::new(
"another_deprecated",
"group2",
"abc",
Some("will be removed"),
"module_name",
),
];
let expected = GENERATED_FILE_COMMENT.to_string()
+ &[
"{",
" store.register_removed(",
" \"clippy::should_assert_eq\",",
" \"has been superseded by should_assert_eq2\",",
" );",
" store.register_removed(",
" \"clippy::another_deprecated\",",
" \"will be removed\",",
" );",
"}",
]
.join("\n")
+ "\n";
assert_eq!(expected, gen_deprecated(lints.iter()));
}
#[test]
#[should_panic]
fn test_gen_deprecated_fail() {
let lints = vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")];
let _deprecated_lints = gen_deprecated(lints.iter());
}
#[test]
fn test_gen_modules_list() {
let lints = vec![
Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
Lint::new("incorrect_stuff", "group3", "abc", None, "another_module"),
];
let expected = vec!["mod another_module;".to_string(), "mod module_name;".to_string()];
assert_eq!(expected, gen_modules_list(lints.iter()));
}
#[test]
fn test_gen_lint_group_list() {
let lints = vec![
Lint::new("abc", "group1", "abc", None, "module_name"),
Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
Lint::new("internal", "internal_style", "abc", None, "module_name"),
];
let expected = GENERATED_FILE_COMMENT.to_string()
+ &[
"store.register_group(true, \"clippy::group1\", Some(\"clippy_group1\"), vec![",
" LintId::of(module_name::ABC),",
" LintId::of(module_name::INTERNAL),",
" LintId::of(module_name::SHOULD_ASSERT_EQ),",
"])",
]
.join("\n")
+ "\n";
let result = gen_lint_group_list("group1", lints.iter());
assert_eq!(expected, result);
}
}
|
use crate::gb::cpu::CPU;
pub mod blu {
use crate::gb::cpu::CPU;
pub fn rlc_n(cpu: &mut CPU, n: u8) -> u8 {
0
}
pub fn rrc_n(cpu: &mut CPU, n: u8) -> u8 {
0
}
pub fn rl_n(cpu: &mut CPU, n: u8) -> u8 {
0
}
pub fn rr_n(cpu: &mut CPU, n: u8) -> u8 {
0
}
pub fn sla_n(cpu: &mut CPU, n: u8) -> u8 {
0
}
pub fn sra_n(cpu: &mut CPU, n: u8) -> u8 {
0
}
pub fn swap_n(cpu: &mut CPU, n: u8) -> u8 {
let res = ((n & 0x0f).wrapping_shl(4)) | ((n & 0xf0).wrapping_shr(4)) as u8;
cpu.reg.set_z_flag(res == 0);
cpu.reg.set_n_flag(false);
cpu.reg.set_h_flag(false);
cpu.reg.set_c_flag(false);
res
}
pub fn srl_n(cpu: &mut CPU, n: u8) -> u8 {
0
}
pub fn bit_b_n(cpu: &mut CPU, n: u8) -> u8 {
0
}
pub fn res_b_n(cpu: &mut CPU, n: u8) -> u8 {
0
}
pub fn set_b_n(cpu: &mut CPU, n: u8) -> u8 {
0
}
}
pub fn swap_a(cpu: &mut CPU) -> usize {
cpu.reg.a = blu::swap_n(cpu, cpu.reg.a);
8
} |
//! Support for compiling with Lightbeam.
use crate::compilation::{CompileError, CompiledFunction, Compiler};
use crate::cranelift::{RelocSink, TrapSink};
use crate::func_environ::FuncEnvironment;
use crate::{FunctionBodyData, ModuleTranslation};
use cranelift_codegen::isa;
use cranelift_wasm::DefinedFuncIndex;
use lightbeam::{CodeGenSession, NullOffsetSink, Sinks};
/// A compiler that compiles a WebAssembly module with Lightbeam, directly translating the Wasm file.
pub struct Lightbeam;
impl Compiler for Lightbeam {
fn compile_function(
&self,
translation: &ModuleTranslation,
i: DefinedFuncIndex,
function_body: &FunctionBodyData<'_>,
isa: &dyn isa::TargetIsa,
) -> Result<CompiledFunction, CompileError> {
if translation.tunables.debug_info {
return Err(CompileError::DebugInfoNotSupported);
}
let func_index = translation.module.func_index(i);
let env = FuncEnvironment::new(
isa.frontend_config(),
&translation.module,
&translation.tunables,
);
let mut codegen_session: CodeGenSession<_> = CodeGenSession::new(
translation.function_body_inputs.len() as u32,
&env,
lightbeam::microwasm::I32,
);
let mut reloc_sink = RelocSink::new(func_index);
let mut trap_sink = TrapSink::new();
lightbeam::translate_function(
&mut codegen_session,
Sinks {
relocs: &mut reloc_sink,
traps: &mut trap_sink,
offsets: &mut NullOffsetSink,
},
i.as_u32(),
wasmparser::FunctionBody::new(0, function_body.data),
)
.map_err(|e| CompileError::Codegen(format!("Failed to translate function: {}", e)))?;
let code_section = codegen_session
.into_translated_code_section()
.map_err(|e| CompileError::Codegen(format!("Failed to generate output code: {}", e)))?;
Ok(CompiledFunction {
// TODO: try to remove copy here (?)
body: code_section.buffer().to_vec(),
traps: trap_sink.traps,
relocations: reloc_sink.func_relocs,
// not implemented for lightbeam currently
unwind_info: None,
stack_maps: Default::default(),
stack_slots: Default::default(),
value_labels_ranges: Default::default(),
address_map: Default::default(),
jt_offsets: Default::default(),
})
}
}
|
// Copyright 2020-2021, The Tremor Team
//
// 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.
//! # File Offramp
//!
//! Writes events to a file, one event per line
//!
//! ## Configuration
//!
//! See [Config](struct.Config.html) for details.
#![cfg(not(tarpaulin_include))]
use crate::connectors::gcp::pubsub_auth::AuthedService;
use crate::connectors::gcp::{pubsub, pubsub_auth};
use crate::connectors::qos::{self, QoSFacilities, SinkQoS};
use crate::sink::prelude::*;
use googapis::google::pubsub::v1::publisher_client::PublisherClient;
use googapis::google::pubsub::v1::subscriber_client::SubscriberClient;
use halfbrown::HashMap;
use tremor_pipeline::{EventIdGenerator, OpMeta};
use tremor_value::Value;
pub struct GoogleCloudPubSub {
remote_publisher: Option<PublisherClient<AuthedService>>,
remote_subscriber: Option<SubscriberClient<AuthedService>>,
is_down: bool,
qos_facility: Box<dyn SinkQoS>,
reply_channel: Option<Sender<sink::Reply>>,
is_linked: bool,
postprocessors: Postprocessors,
event_id_gen: EventIdGenerator,
}
enum PubSubCommand {
SendMessage {
project_id: String,
topic_name: String,
data: Value<'static>,
ordering_key: String,
},
CreateSubscription {
project_id: String,
topic_name: String,
subscription_name: String,
enable_message_ordering: bool,
},
Unknown,
}
impl std::fmt::Display for PubSubCommand {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"{}",
match *self {
PubSubCommand::SendMessage {
project_id: _,
topic_name: _,
data: _,
ordering_key: _,
} => "send_message",
PubSubCommand::CreateSubscription {
project_id: _,
topic_name: _,
subscription_name: _,
enable_message_ordering: _,
} => "create_subscription",
PubSubCommand::Unknown => "Unknown",
}
)
}
}
impl offramp::Impl for GoogleCloudPubSub {
fn from_config(_config: &Option<OpConfig>) -> Result<Box<dyn Offramp>> {
let hostport = "pubsub.googleapis.com:443";
Ok(SinkManager::new_box(Self {
remote_publisher: None, // overwritten in init
remote_subscriber: None, // overwritten in init
is_down: false,
qos_facility: Box::new(QoSFacilities::recoverable(hostport.to_string())),
reply_channel: None,
is_linked: false,
postprocessors: vec![],
event_id_gen: EventIdGenerator::new(0), // Fake ID overwritten in init
}))
}
}
fn parse_arg(field_name: &'static str, o: &Value) -> std::result::Result<String, String> {
o.get_str(field_name)
.map(ToString::to_string)
.ok_or_else(|| format!("Invalid Command, expected `{}` field", field_name))
}
fn parse_command(value: &Value) -> Result<PubSubCommand> {
let cmd_name: &str = value
.get_str("command")
.ok_or("Invalid Command, expected `command` field")?;
let command = match cmd_name {
"send_message" => PubSubCommand::SendMessage {
project_id: parse_arg("project", value)?,
topic_name: parse_arg("topic", value)?,
data: value
.get("data")
.map(Value::clone_static)
.ok_or("Invalid Command, expected `data` field")?,
ordering_key: parse_arg("ordering_key", value)?,
},
"create_subscription" => PubSubCommand::CreateSubscription {
project_id: parse_arg("project", value)?,
topic_name: parse_arg("topic", value)?,
subscription_name: parse_arg("subscription", value)?,
enable_message_ordering: value.get_bool("message_ordering").unwrap_or_default(),
},
_ => PubSubCommand::Unknown,
};
Ok(command)
}
#[async_trait::async_trait]
impl Sink for GoogleCloudPubSub {
async fn terminate(&mut self) {}
#[allow(clippy::too_many_lines)]
async fn on_event(
&mut self,
_input: &str,
codec: &mut dyn Codec,
_codec_map: &HashMap<String, Box<dyn Codec>>,
mut event: Event,
) -> ResultVec {
let remote_publisher = if let Some(remote_publisher) = &mut self.remote_publisher {
remote_publisher
} else {
self.remote_publisher = Some(pubsub_auth::setup_publisher_client().await?);
let remote_publisher = self
.remote_publisher
.as_mut()
.ok_or("Publisher client error!")?;
remote_publisher
// TODO - Qos checks
};
let remote_subscriber = if let Some(remote_subscriber) = &mut self.remote_subscriber {
remote_subscriber
} else {
self.remote_subscriber = Some(pubsub_auth::setup_subscriber_client().await?);
let remote_subscriber = self
.remote_subscriber
.as_mut()
.ok_or("Subscriber client error!")?;
remote_subscriber
// TODO - Qos checks
};
let maybe_correlation = event.correlation_meta();
let mut response = Vec::new();
for value in event.value_iter() {
let command = parse_command(value)?;
match command {
PubSubCommand::SendMessage {
project_id,
topic_name,
data,
ordering_key,
} => {
let mut msg: Vec<u8> = vec![];
let encoded = codec.encode(&data)?;
let mut processed =
postprocess(&mut self.postprocessors, event.ingest_ns, encoded)?;
for processed_elem in &mut processed {
msg.append(processed_elem);
}
response.push(make_command_response(
"send_message",
&pubsub::send_message(
remote_publisher,
&project_id,
&topic_name,
&msg,
&ordering_key,
)
.await?,
));
}
PubSubCommand::CreateSubscription {
project_id,
topic_name,
subscription_name,
enable_message_ordering,
} => {
let res = pubsub::create_subscription(
remote_subscriber,
&project_id,
&topic_name,
&subscription_name,
enable_message_ordering,
)
.await?;
// The commented fields can be None and throw error, and the data type was also not compatible - hence not included in response
let subscription = res.name;
let topic = res.topic;
// let push_config = res.push_config.ok_or("Error getting `push_config` for the created subscription")?;
let ack_deadline_seconds = res.ack_deadline_seconds;
let retain_acked_messages = res.retain_acked_messages;
let enable_message_ordering = res.enable_message_ordering;
// let labels = res.labels;
let message_retention_duration = res.message_retention_duration.ok_or("Error getting `message retention duration` for the created subscription")?.seconds;
// let expiration_policy = res.expiration_policy.ok_or("Error getting `expiration policy` for the created subscription")?;
let filter = res.filter;
// let dead_letter_policy = res.dead_letter_policy.ok_or("Error getting `dead letter policy` for the created subscription")?;
// let retry_policy = res.retry_policy.ok_or("Error getting `retry policy` for the created subscription")?;
let detached = res.detached;
response.push(literal!({
"subscription": subscription,
"topic": topic,
"ack_deadline_seconds": ack_deadline_seconds,
"retain_acked_messages": retain_acked_messages,
"enable_message_ordering": enable_message_ordering,
"message_retention_duration": message_retention_duration,
"filter": filter,
"detached": detached
}));
}
PubSubCommand::Unknown => {
warn!(
"Unknown Google Cloud PubSub command: `{}` attempted",
command.to_string()
);
return Err(format!(
"Unknown Google Cloud PubSub command: `{}` attempted",
command.to_string()
)
.into());
}
};
}
if self.is_linked {
if let Some(reply_channel) = &self.reply_channel {
let mut meta = Object::with_capacity(1);
if let Some(correlation) = maybe_correlation {
meta.insert_nocheck("correlation".into(), correlation);
}
// The response vector will have only one value currently since this version of `gpub` doesn't support batches
// So we pop that value out send it as response
let val = response.pop().ok_or("No response received from GCP")?;
reply_channel
.send(sink::Reply::Response(
OUT,
Event {
id: self.event_id_gen.next_id(),
data: (val, meta).into(),
ingest_ns: nanotime(),
origin_uri: Some(EventOriginUri {
uid: 0,
scheme: "gRPC".into(),
host: "".into(),
port: None,
path: vec![],
}),
kind: None,
is_batch: false,
cb: CbAction::None,
op_meta: OpMeta::default(),
transactional: false,
},
))
.await?;
}
}
self.is_down = false;
Ok(Some(vec![qos::ack(&mut event)]))
}
fn default_codec(&self) -> &str {
"json"
}
#[allow(clippy::too_many_arguments)]
async fn init(
&mut self,
sink_uid: u64,
_sink_url: &TremorUrl,
_codec: &dyn Codec,
_codec_map: &HashMap<String, Box<dyn Codec>>,
processors: Processors<'_>,
is_linked: bool,
reply_channel: Sender<sink::Reply>,
) -> Result<()> {
self.remote_publisher = Some(pubsub_auth::setup_publisher_client().await?);
self.remote_subscriber = Some(pubsub_auth::setup_subscriber_client().await?);
self.event_id_gen = EventIdGenerator::new(sink_uid);
self.postprocessors = make_postprocessors(processors.post)?;
self.reply_channel = Some(reply_channel);
self.is_linked = is_linked;
Ok(())
}
async fn on_signal(&mut self, mut signal: Event) -> ResultVec {
if self.is_down && self.qos_facility.probe(signal.ingest_ns) {
self.is_down = false;
// This means the port is connectable
info!("Google Cloud PubSub - sink remote endpoint - recovered and contactable");
self.is_down = false;
return Ok(Some(vec![qos::open(&mut signal)]));
}
Ok(None)
}
fn is_active(&self) -> bool {
true
}
fn auto_ack(&self) -> bool {
false
}
}
fn make_command_response(cmd: &str, message_id: &str) -> Value<'static> {
literal!({
"command": cmd,
"message-id": message_id
})
.into_static()
}
|
extern crate libc;
use std::ffi::CStr;
use std::str::from_utf8;
use native::libssh;
pub fn from_native_str<'a>(native_str: *const libc::c_char)
-> Result<&'a str, &'static str> {
if native_str.is_null() {
return Err("Could not convert NULL native string");
}
unsafe {
match from_utf8(CStr::from_ptr(native_str).to_bytes()) {
Ok(s) => Ok(s),
Err(_) => Err("Could not convert native string to String")
}
}
}
pub fn ssh_get_error(ptr: *mut libc::c_void)
-> Result<&'static str, &'static str> {
let err = unsafe {
libssh::ssh_get_error(ptr)
};
if err.is_null() {
Err("Unknown SSH error")
} else {
from_native_str(err)
}
}
/*
trait SSHErrorMessage {
fn get_error(&self) -> &'static str;
}
*/
#[macro_export]
macro_rules! ssh_err_msg {
($ptr: expr, $cause: expr) => {
match $crate::util::ssh_get_error($ptr as *mut libc::c_void) {
Ok(err_str) => err_str,
Err(_) => concat!(stringify!($cause),
" failed (could not get libssh error)")
}
}
}
macro_rules! _check_ssh_ok {
($e: expr, $error: expr) => {
match unsafe { $e } {
libssh::SSH_OK => Ok(()),
_ => {Err($error)}
}
}
}
/// Checks that the return value of a given function is SSH_OK.
/// unsafe expr(, *mut ptr) -> Result<(), &str>
#[macro_export]
macro_rules! check_ssh_ok {
($e: expr) => {
_check_ssh_ok!($e, concat!(stringify!($e), " failed"))
};
($e: expr, $ptr: expr) => {
_check_ssh_ok!($e, ssh_err_msg!($ptr, $e))
}
}
macro_rules! _check_ssh_ptr {
($e: expr, $error: expr) => {
{
let res = unsafe { $e };
if res.is_null(){
Err($error)
} else {
Ok(res)
}
}
}
}
/// Checks that the return value of a given function is not null.
/// unsafe expr(, *mut ptr) -> Result<(), &str>
#[macro_export]
macro_rules! check_ssh_ptr {
($e: expr) => {
_check_ssh_ptr!($e, concat!(stringify!($e), " failed"))
};
($e: expr, $ptr: expr) => {
_check_ssh_ptr!($e, ssh_err_msg!($ptr, $e))
}
}
|
use bitflags::bitflags;
use bytes::{Buf, Bytes};
use encoding_rs::Encoding;
use crate::encode::{Encode, IsNull};
use crate::error::Error;
use crate::mssql::Mssql;
bitflags! {
#[cfg_attr(feature = "offline", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct CollationFlags: u8 {
const IGNORE_CASE = (1 << 0);
const IGNORE_ACCENT = (1 << 1);
const IGNORE_WIDTH = (1 << 2);
const IGNORE_KANA = (1 << 3);
const BINARY = (1 << 4);
const BINARY2 = (1 << 5);
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "offline", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct Collation {
pub(crate) locale: u32,
pub(crate) flags: CollationFlags,
pub(crate) sort: u8,
pub(crate) version: u8,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "offline", derive(serde::Serialize, serde::Deserialize))]
#[repr(u8)]
pub(crate) enum DataType {
// fixed-length data types
// https://docs.microsoft.com/en-us/openspecs/sql_server_protocols/ms-sstds/d33ef17b-7e53-4380-ad11-2ba42c8dda8d
Null = 0x1f,
TinyInt = 0x30,
Bit = 0x32,
SmallInt = 0x34,
Int = 0x38,
SmallDateTime = 0x3a,
Real = 0x3b,
Money = 0x3c,
DateTime = 0x3d,
Float = 0x3e,
SmallMoney = 0x7a,
BigInt = 0x7f,
// variable-length data types
// https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-tds/ce3183a6-9d89-47e8-a02f-de5a1a1303de
// byte length
Guid = 0x24,
IntN = 0x26,
Decimal = 0x37, // legacy
Numeric = 0x3f, // legacy
BitN = 0x68,
DecimalN = 0x6a,
NumericN = 0x6c,
FloatN = 0x6d,
MoneyN = 0x6e,
DateTimeN = 0x6f,
DateN = 0x28,
TimeN = 0x29,
DateTime2N = 0x2a,
DateTimeOffsetN = 0x2b,
Char = 0x2f, // legacy
VarChar = 0x27, // legacy
Binary = 0x2d, // legacy
VarBinary = 0x25, // legacy
// short length
BigVarBinary = 0xa5,
BigVarChar = 0xa7,
BigBinary = 0xad,
BigChar = 0xaf,
NVarChar = 0xe7,
NChar = 0xef,
Xml = 0xf1,
UserDefined = 0xf0,
// long length
Text = 0x23,
Image = 0x22,
NText = 0x63,
Variant = 0x62,
}
// http://msdn.microsoft.com/en-us/library/dd358284.aspx
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "offline", derive(serde::Serialize, serde::Deserialize))]
pub(crate) struct TypeInfo {
pub(crate) ty: DataType,
pub(crate) size: u32,
pub(crate) scale: u8,
pub(crate) precision: u8,
pub(crate) collation: Option<Collation>,
}
impl TypeInfo {
pub(crate) const fn new(ty: DataType, size: u32) -> Self {
Self {
ty,
size,
scale: 0,
precision: 0,
collation: None,
}
}
pub(crate) fn encoding(&self) -> Result<&'static Encoding, Error> {
match self.ty {
DataType::NChar | DataType::NVarChar => Ok(encoding_rs::UTF_16LE),
DataType::VarChar | DataType::Char | DataType::BigChar | DataType::BigVarChar => {
// unwrap: impossible to unwrap here, collation will be set
Ok(match self.collation.unwrap().locale {
// This is the Western encoding for Windows. It is an extension of ISO-8859-1,
// which is known as Latin 1.
0x0409 => encoding_rs::WINDOWS_1252,
locale => {
return Err(err_protocol!("unsupported locale 0x{:?}", locale));
}
})
}
_ => {
// default to UTF-8 for anything
// else coming in here
Ok(encoding_rs::UTF_8)
}
}
}
// reads a TYPE_INFO from the buffer
pub(crate) fn get(buf: &mut Bytes) -> Result<Self, Error> {
let ty = DataType::get(buf)?;
Ok(match ty {
DataType::Null => Self::new(ty, 0),
DataType::TinyInt | DataType::Bit => Self::new(ty, 1),
DataType::SmallInt => Self::new(ty, 2),
DataType::Int | DataType::SmallDateTime | DataType::Real | DataType::SmallMoney => {
Self::new(ty, 4)
}
DataType::BigInt | DataType::Money | DataType::DateTime | DataType::Float => {
Self::new(ty, 8)
}
DataType::DateN => Self::new(ty, 3),
DataType::TimeN | DataType::DateTime2N | DataType::DateTimeOffsetN => {
let scale = buf.get_u8();
let mut size = match scale {
0 | 1 | 2 => 3,
3 | 4 => 4,
5 | 6 | 7 => 5,
scale => {
return Err(err_protocol!("invalid scale {} for type {:?}", scale, ty));
}
};
match ty {
DataType::DateTime2N => {
size += 3;
}
DataType::DateTimeOffsetN => {
size += 5;
}
_ => {}
}
Self {
scale,
size,
ty,
precision: 0,
collation: None,
}
}
DataType::Guid
| DataType::IntN
| DataType::BitN
| DataType::FloatN
| DataType::MoneyN
| DataType::DateTimeN
| DataType::Char
| DataType::VarChar
| DataType::Binary
| DataType::VarBinary => Self::new(ty, buf.get_u8() as u32),
DataType::Decimal | DataType::Numeric | DataType::DecimalN | DataType::NumericN => {
let size = buf.get_u8() as u32;
let precision = buf.get_u8();
let scale = buf.get_u8();
Self {
size,
precision,
scale,
ty,
collation: None,
}
}
DataType::BigVarBinary | DataType::BigBinary => Self::new(ty, buf.get_u16_le() as u32),
DataType::BigVarChar | DataType::BigChar | DataType::NVarChar | DataType::NChar => {
let size = buf.get_u16_le() as u32;
let collation = Collation::get(buf);
Self {
ty,
size,
collation: Some(collation),
scale: 0,
precision: 0,
}
}
_ => {
return Err(err_protocol!("unsupported data type {:?}", ty));
}
})
}
// writes a TYPE_INFO to the buffer
pub(crate) fn put(&self, buf: &mut Vec<u8>) {
buf.push(self.ty as u8);
match self.ty {
DataType::Null
| DataType::TinyInt
| DataType::Bit
| DataType::SmallInt
| DataType::Int
| DataType::SmallDateTime
| DataType::Real
| DataType::SmallMoney
| DataType::BigInt
| DataType::Money
| DataType::DateTime
| DataType::Float
| DataType::DateN => {
// nothing to do
}
DataType::TimeN | DataType::DateTime2N | DataType::DateTimeOffsetN => {
buf.push(self.scale);
}
DataType::Guid
| DataType::IntN
| DataType::BitN
| DataType::FloatN
| DataType::MoneyN
| DataType::DateTimeN
| DataType::Char
| DataType::VarChar
| DataType::Binary
| DataType::VarBinary => {
buf.push(self.size as u8);
}
DataType::Decimal | DataType::Numeric | DataType::DecimalN | DataType::NumericN => {
buf.push(self.size as u8);
buf.push(self.precision);
buf.push(self.scale);
}
DataType::BigVarBinary | DataType::BigBinary => {
buf.extend(&(self.size as u16).to_le_bytes());
}
DataType::BigVarChar | DataType::BigChar | DataType::NVarChar | DataType::NChar => {
buf.extend(&(self.size as u16).to_le_bytes());
if let Some(collation) = &self.collation {
collation.put(buf);
} else {
buf.extend(&0_u32.to_le_bytes());
buf.push(0);
}
}
_ => {
unimplemented!("unsupported data type {:?}", self.ty);
}
}
}
pub(crate) fn is_null(&self) -> bool {
matches!(self.ty, DataType::Null)
}
pub(crate) fn get_value(&self, buf: &mut Bytes) -> Option<Bytes> {
match self.ty {
DataType::Null
| DataType::TinyInt
| DataType::Bit
| DataType::SmallInt
| DataType::Int
| DataType::SmallDateTime
| DataType::Real
| DataType::Money
| DataType::DateTime
| DataType::Float
| DataType::SmallMoney
| DataType::BigInt => Some(buf.split_to(self.size as usize)),
DataType::Guid
| DataType::IntN
| DataType::Decimal
| DataType::Numeric
| DataType::BitN
| DataType::DecimalN
| DataType::NumericN
| DataType::FloatN
| DataType::MoneyN
| DataType::DateTimeN
| DataType::DateN
| DataType::TimeN
| DataType::DateTime2N
| DataType::DateTimeOffsetN => {
let size = buf.get_u8();
if size == 0 || size == 0xFF {
None
} else {
Some(buf.split_to(size as usize))
}
}
DataType::Char | DataType::VarChar | DataType::Binary | DataType::VarBinary => {
let size = buf.get_u8();
if size == 0xFF {
None
} else {
Some(buf.split_to(size as usize))
}
}
DataType::BigVarBinary
| DataType::BigVarChar
| DataType::BigBinary
| DataType::BigChar
| DataType::NVarChar
| DataType::NChar
| DataType::Xml
| DataType::UserDefined => {
let size = buf.get_u16_le();
if size == 0xFF_FF {
None
} else {
Some(buf.split_to(size as usize))
}
}
DataType::Text | DataType::Image | DataType::NText | DataType::Variant => {
let size = buf.get_u32_le();
if size == 0xFFFF_FFFF {
None
} else {
Some(buf.split_to(size as usize))
}
}
}
}
pub(crate) fn put_value<'q, T: Encode<'q, Mssql>>(&self, buf: &mut Vec<u8>, value: T) {
match self.ty {
DataType::Null
| DataType::TinyInt
| DataType::Bit
| DataType::SmallInt
| DataType::Int
| DataType::SmallDateTime
| DataType::Real
| DataType::Money
| DataType::DateTime
| DataType::Float
| DataType::SmallMoney
| DataType::BigInt => {
self.put_fixed_value(buf, value);
}
DataType::Guid
| DataType::IntN
| DataType::Decimal
| DataType::Numeric
| DataType::BitN
| DataType::DecimalN
| DataType::NumericN
| DataType::FloatN
| DataType::MoneyN
| DataType::DateTimeN
| DataType::DateN
| DataType::TimeN
| DataType::DateTime2N
| DataType::DateTimeOffsetN
| DataType::Char
| DataType::VarChar
| DataType::Binary
| DataType::VarBinary => {
self.put_byte_len_value(buf, value);
}
DataType::BigVarBinary
| DataType::BigVarChar
| DataType::BigBinary
| DataType::BigChar
| DataType::NVarChar
| DataType::NChar
| DataType::Xml
| DataType::UserDefined => {
self.put_short_len_value(buf, value);
}
DataType::Text | DataType::Image | DataType::NText | DataType::Variant => {
self.put_long_len_value(buf, value);
}
}
}
pub(crate) fn put_fixed_value<'q, T: Encode<'q, Mssql>>(&self, buf: &mut Vec<u8>, value: T) {
let _ = value.encode(buf);
}
pub(crate) fn put_byte_len_value<'q, T: Encode<'q, Mssql>>(&self, buf: &mut Vec<u8>, value: T) {
let offset = buf.len();
buf.push(0);
let size = if let IsNull::Yes = value.encode(buf) {
0xFF
} else {
(buf.len() - offset - 1) as u8
};
buf[offset] = size;
}
pub(crate) fn put_short_len_value<'q, T: Encode<'q, Mssql>>(
&self,
buf: &mut Vec<u8>,
value: T,
) {
let offset = buf.len();
buf.extend(&0_u16.to_le_bytes());
let size = if let IsNull::Yes = value.encode(buf) {
0xFFFF
} else {
(buf.len() - offset - 2) as u16
};
buf[offset..(offset + 2)].copy_from_slice(&size.to_le_bytes());
}
pub(crate) fn put_long_len_value<'q, T: Encode<'q, Mssql>>(&self, buf: &mut Vec<u8>, value: T) {
let offset = buf.len();
buf.extend(&0_u32.to_le_bytes());
let size = if let IsNull::Yes = value.encode(buf) {
0xFFFF_FFFF
} else {
(buf.len() - offset - 4) as u32
};
buf[offset..(offset + 4)].copy_from_slice(&size.to_le_bytes());
}
pub(crate) fn name(&self) -> &'static str {
match self.ty {
DataType::Null => "NULL",
DataType::TinyInt => "TINYINT",
DataType::SmallInt => "SMALLINT",
DataType::Int => "INT",
DataType::BigInt => "BIGINT",
DataType::Real => "REAL",
DataType::Float => "FLOAT",
DataType::IntN => match self.size {
1 => "TINYINT",
2 => "SMALLINT",
4 => "INT",
8 => "BIGINT",
n => unreachable!("invalid size {} for int", n),
},
DataType::FloatN => match self.size {
4 => "REAL",
8 => "FLOAT",
n => unreachable!("invalid size {} for float", n),
},
DataType::VarChar => "VARCHAR",
DataType::NVarChar => "NVARCHAR",
DataType::BigVarChar => "BIGVARCHAR",
DataType::Char => "CHAR",
DataType::BigChar => "BIGCHAR",
DataType::NChar => "NCHAR",
_ => unimplemented!("name: unsupported data type {:?}", self.ty),
}
}
pub(crate) fn fmt(&self, s: &mut String) {
match self.ty {
DataType::Null => s.push_str("nvarchar(1)"),
DataType::TinyInt => s.push_str("tinyint"),
DataType::SmallInt => s.push_str("smallint"),
DataType::Int => s.push_str("int"),
DataType::BigInt => s.push_str("bigint"),
DataType::Real => s.push_str("real"),
DataType::Float => s.push_str("float"),
DataType::Bit => s.push_str("bit"),
DataType::IntN => s.push_str(match self.size {
1 => "tinyint",
2 => "smallint",
4 => "int",
8 => "bigint",
n => unreachable!("invalid size {} for int", n),
}),
DataType::FloatN => s.push_str(match self.size {
4 => "real",
8 => "float",
n => unreachable!("invalid size {} for float", n),
}),
DataType::VarChar
| DataType::NVarChar
| DataType::BigVarChar
| DataType::Char
| DataType::BigChar
| DataType::NChar => {
// name
s.push_str(match self.ty {
DataType::VarChar => "varchar",
DataType::NVarChar => "nvarchar",
DataType::BigVarChar => "bigvarchar",
DataType::Char => "char",
DataType::BigChar => "bigchar",
DataType::NChar => "nchar",
_ => unreachable!(),
});
// size
if self.size < 8000 && self.size > 0 {
s.push_str("(");
s.push_str(itoa::Buffer::new().format(self.size));
s.push_str(")");
} else {
s.push_str("(max)");
}
}
DataType::BitN => {
s.push_str("bit");
}
_ => unimplemented!("fmt: unsupported data type {:?}", self.ty),
}
}
}
impl DataType {
pub(crate) fn get(buf: &mut Bytes) -> Result<Self, Error> {
Ok(match buf.get_u8() {
0x1f => DataType::Null,
0x30 => DataType::TinyInt,
0x32 => DataType::Bit,
0x34 => DataType::SmallInt,
0x38 => DataType::Int,
0x3a => DataType::SmallDateTime,
0x3b => DataType::Real,
0x3c => DataType::Money,
0x3d => DataType::DateTime,
0x3e => DataType::Float,
0x7a => DataType::SmallMoney,
0x7f => DataType::BigInt,
0x24 => DataType::Guid,
0x26 => DataType::IntN,
0x37 => DataType::Decimal,
0x3f => DataType::Numeric,
0x68 => DataType::BitN,
0x6a => DataType::DecimalN,
0x6c => DataType::NumericN,
0x6d => DataType::FloatN,
0x6e => DataType::MoneyN,
0x6f => DataType::DateTimeN,
0x28 => DataType::DateN,
0x29 => DataType::TimeN,
0x2a => DataType::DateTime2N,
0x2b => DataType::DateTimeOffsetN,
0x2f => DataType::Char,
0x27 => DataType::VarChar,
0x2d => DataType::Binary,
0x25 => DataType::VarBinary,
0xa5 => DataType::BigVarBinary,
0xa7 => DataType::BigVarChar,
0xad => DataType::BigBinary,
0xaf => DataType::BigChar,
0xe7 => DataType::NVarChar,
0xef => DataType::NChar,
0xf1 => DataType::Xml,
0xf0 => DataType::UserDefined,
0x23 => DataType::Text,
0x22 => DataType::Image,
0x63 => DataType::NText,
0x62 => DataType::Variant,
ty => {
return Err(err_protocol!("unknown data type 0x{:02x}", ty));
}
})
}
}
impl Collation {
pub(crate) fn get(buf: &mut Bytes) -> Collation {
let locale_sort_version = buf.get_u32_le();
let locale = locale_sort_version & 0xfffff;
let flags = CollationFlags::from_bits_truncate(((locale_sort_version >> 20) & 0xFF) as u8);
let version = (locale_sort_version >> 28) as u8;
let sort = buf.get_u8();
Collation {
locale,
flags,
sort,
version,
}
}
pub(crate) fn put(&self, buf: &mut Vec<u8>) {
let locale_sort_version =
self.locale | ((self.flags.bits() as u32) << 20) | ((self.version as u32) << 28);
buf.extend(&locale_sort_version.to_le_bytes());
buf.push(self.sort);
}
}
#[test]
fn test_get() {
#[rustfmt::skip]
let mut buf = Bytes::from_static(&[
0x26, 4, 4, 1, 0, 0, 0, 0xfe, 0, 0, 0xe0, 0, 0, 0, 0, 0, 0, 0, 0, 0
]);
let type_info = TypeInfo::get(&mut buf).unwrap();
assert_eq!(type_info, TypeInfo::new(DataType::IntN, 4));
}
|
use std::sync::{Arc, Mutex};
use tokio::sync::watch;
use tokio::time::{delay_for, Duration};
const MAX_ID: u32 = 10;
struct ME {
last_log_index_tx: watch::Sender<u32>,
last_log_index_rx: watch::Receiver<u32>,
}
#[tokio::test]
async fn main() {
let (tx, rx) = watch::channel(0);
let me = ME {
last_log_index_tx: tx,
last_log_index_rx: rx,
};
let me = Arc::new(Mutex::new(me));
let mut handles = vec![];
let mm = me.clone();
let tx_handle = tokio::spawn(async move {
for id in 1..=MAX_ID {
delay_for(Duration::from_millis(100)).await;
let me = mm.lock().unwrap();
me.last_log_index_tx.broadcast(id);
}
});
for id in 1..=MAX_ID {
let mm = me.clone();
handles.push(tokio::spawn(async move {
let mut rx = {
let me = mm.lock().unwrap();
me.last_log_index_rx.clone()
};
while let Some(index) = rx.recv().await {
println!("received = {:?}", index);
if index >= id {
return;
}
}
}));
}
tokio::join!(tx_handle);
for handle in handles {
tokio::join!(handle);
}
}
|
extern crate tempfile;
use std::collections::HashMap;
use std::fs::{create_dir, File};
use std::io::Write;
use std::process::{Child as ChildProcess, Stdio};
use tempfile::tempdir;
#[test]
fn roundtrip() -> Result<(), Box<dyn std::error::Error>> {
let dir = tempdir()?;
let files: HashMap<String, String> = (0..10)
.map(|i| (format!("file{}", i), format!("test content for file number {}", i)))
.collect();
let test_data_dir = dir.path().join("test-data");
create_dir(&test_data_dir)?;
for (name, content) in &files {
let mut file = File::create(test_data_dir.join(name))?;
file.write_all(content.as_bytes())?;
}
let build = escargot::CargoBuild::new()
.run()?
.command()
.current_dir(dir.path())
.arg("build")
.arg(dir.path().join("test-data").as_os_str())
.arg("files")
.status()?;
if !build.success() {
return Err("failed to build archive".into());
}
let server = Server::start(dir.path().join("files.archive").as_os_str())?;
std::thread::sleep(std::time::Duration::from_millis(200));
for (name, content) in &files {
let res = reqwest::Client::builder()
.gzip(true)
.timeout(std::time::Duration::from_millis(200))
.build()?
.get(&format!("http://localhost:{}/{}", server.port()?, name))
.send()?
.text()?;
assert_eq!(&res, content);
}
Ok(())
}
struct Server {
process: ChildProcess,
}
impl Server {
/// Somewhat random, lol
const PORT: u16 = 60814;
fn start(archive_file: &std::ffi::OsStr) -> Result<Server, Box<dyn std::error::Error>> {
let process = escargot::CargoBuild::new()
.run()?
.command()
.arg("serve")
.arg(format!("--port={}", Self::PORT))
.arg(archive_file)
.stdout(Stdio::null())
.spawn()?;
Ok(Server { process })
}
fn port(&self) -> Result<u16, Box<dyn std::error::Error>> {
Ok(Self::PORT)
}
}
impl Drop for Server {
fn drop(&mut self) {
self.process.kill().unwrap();
}
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
pub const D3DCOMPILER_DLL: &'static str = "d3dcompiler_47.dll";
pub const D3DCOMPILE_OPTIMIZATION_LEVEL2: u32 = 49152u32;
pub const D3D_COMPILE_STANDARD_FILE_INCLUDE: u32 = 1u32;
|
use std::collections::BinaryHeap;
use crate::algos::book::{Book, Order, Side, Trade};
/// Price-time priority (or FIFO) matching engine implemented using a [BinaryHeap].
///
/// Implemented as a state-machine to be used for replication with Raft.
#[derive(Debug, Clone)]
pub struct FIFOBook {
asks: BinaryHeap<Order>,
bids: BinaryHeap<Order>,
}
impl FIFOBook {
pub fn new() -> Self {
Self {
asks: Default::default(),
bids: Default::default(),
}
}
}
impl Book for FIFOBook {
fn apply(&mut self, order: Order) {
match order.side {
Side::Buy => &self.bids.push(order),
Side::Sell => &self.asks.push(order),
};
}
fn check_for_trades(&mut self) -> Vec<Trade> {
let mut trades = vec![];
while let (Some(ask), Some(bid)) = (self.asks.pop(), self.bids.pop()) {
match Order::merge(ask, bid) {
None => break,
Some((trade, remainder)) => {
trades.push(trade);
if let Some(rem) = remainder {
match rem.side {
Side::Buy => self.bids.push(rem),
Side::Sell => self.asks.push(rem),
}
}
}
}
}
trades
}
fn cancel(&mut self, _order_id: (u64, u64), _side: Side) -> bool {
unimplemented!()
}
}
#[cfg(test)]
mod tests {
use rand::Rng;
// Note this useful idiom: importing names from outer (for mod tests) scope.
use super::*;
fn make_default_order(side: Side, price: u64, size: u64) -> Order {
Order {
client_id: 0,
seq_number: 0,
price,
size,
side,
}
}
fn make_default_queue(side: Side) -> BinaryHeap<Order> {
BinaryHeap::from(vec![
make_default_order(side, 0, 10),
make_default_order(side, 3, 25),
make_default_order(side, 2, 50),
])
}
fn make_tradable_ask_queue() -> BinaryHeap<Order> {
BinaryHeap::from(vec![
make_default_order(Side::Sell, 2, 10),
make_default_order(Side::Sell, 3, 25),
make_default_order(Side::Sell, 2, 50),
])
}
fn make_tradable_bid_queue() -> BinaryHeap<Order> {
BinaryHeap::from(vec![
make_default_order(Side::Buy, 1, 1),
make_default_order(Side::Buy, 3, 25),
make_default_order(Side::Buy, 2, 50),
])
}
#[test]
fn test_construction() {
let book = FIFOBook {
asks: make_default_queue(Side::Sell),
bids: make_default_queue(Side::Buy),
};
println!("Hello book!");
println!("Bids: {:?}", &book.bids);
println!("Asks: {:?}", &book.asks);
}
#[test]
fn test_apply() {
let mut book = FIFOBook {
asks: make_default_queue(Side::Sell),
bids: make_default_queue(Side::Buy),
};
book.apply(make_default_order(Side::Sell, 2, 1));
println!("Bids: {:?}", &book.bids);
println!("Asks: {:?}", &book.asks);
assert_eq!(book.asks.len(), 4);
assert_eq!(book.bids.len(), 3);
}
#[test]
fn test_check_trades() {
let mut book = FIFOBook {
asks: make_tradable_ask_queue(),
bids: make_tradable_bid_queue(),
};
let trades = book.check_for_trades();
println!("Bids: {:?}", &book.bids);
println!("Asks: {:?}", &book.asks);
println!("Trades: {:?}", &trades);
assert_eq!(trades.is_empty(), false);
}
#[test]
fn test_check_trades_performance() {
let orders = generate_tradable_orders(1_000_000);
measure_book_performance(orders);
}
fn measure_book_performance(orders: Vec<Order>) {
let mut book = FIFOBook::new();
for order in orders {
book.apply(order);
book.check_for_trades();
}
}
fn generate_tradable_orders(n: u64) -> Vec<Order> {
let mut rand = rand::thread_rng();
let mut last_ask = 0;
let mut last_bid = 0;
let mut orders = vec![];
for _ in 0..n {
let (price, size, side) = if rand.gen_bool(0.5) {
// Generate buy order
let price = std::cmp::max(1, last_ask as i64 + rand.gen_range(-10..10)) as u64;
last_bid = price;
(price, rand.gen_range(0..20), Side::Buy)
} else {
// Generate sell order
let price = std::cmp::max(1, last_bid as i64 + rand.gen_range(-10..10)) as u64;
last_ask = price;
(price, rand.gen_range(0..20), Side::Sell)
};
orders.push(Order {
client_id: 0,
seq_number: 0,
size,
side,
price,
});
}
return orders;
}
}
|
// Copyright 2023 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_ast::ast::ShowColumnsStmt;
use common_ast::ast::ShowLimit;
use common_exception::Result;
use tracing::debug;
use crate::normalize_identifier;
use crate::plans::Plan;
use crate::plans::RewriteKind;
use crate::BindContext;
use crate::Binder;
use crate::SelectBuilder;
impl Binder {
pub(in crate::planner::binder) async fn bind_show_columns(
&mut self,
bind_context: &mut BindContext,
stmt: &ShowColumnsStmt,
) -> Result<Plan> {
let ShowColumnsStmt {
catalog,
database,
table,
full,
limit,
} = stmt;
let catalog_name = match catalog {
None => self.ctx.get_current_catalog(),
Some(ident) => {
let catalog = normalize_identifier(ident, &self.name_resolution_ctx).name;
self.ctx.get_catalog(&catalog)?;
catalog
}
};
let catalog = self.ctx.get_catalog(&catalog_name)?;
let database = match database {
None => self.ctx.get_current_database(),
Some(ident) => {
let database = normalize_identifier(ident, &self.name_resolution_ctx).name;
catalog
.get_database(&self.ctx.get_tenant(), &database)
.await?;
database
}
};
let table = {
let table = normalize_identifier(table, &self.name_resolution_ctx).name;
catalog
.get_table(&self.ctx.get_tenant(), database.as_str(), &table)
.await?;
table
};
let mut select_builder = SelectBuilder::from("information_schema.columns");
select_builder
.with_column("column_name AS `Field`")
.with_column("column_type AS `Type`")
.with_column("is_nullable AS `Null`")
.with_column("default AS `Default`")
.with_column("extra AS `Extra`")
.with_column("column_key AS `Key`");
if *full {
select_builder
.with_column("collation_name AS `Collation`")
.with_column("privileges AS `Privileges`")
.with_column("column_comment AS Comment");
}
select_builder
.with_order_by("table_schema")
.with_order_by("table_name")
.with_order_by("column_name");
select_builder
.with_filter(format!("table_schema = '{database}'"))
.with_filter(format!("table_name = '{table}'"));
let query = match limit {
None => select_builder.build(),
Some(ShowLimit::Like { pattern }) => {
select_builder.with_filter(format!("column_name LIKE '{pattern}'"));
select_builder.build()
}
Some(ShowLimit::Where { selection }) => {
select_builder.with_filter(format!("({selection})"));
select_builder.build()
}
};
debug!("show columns rewrite to: {:?}", query);
self.bind_rewrite_to_query(bind_context, query.as_str(), RewriteKind::ShowColumns)
.await
}
}
|
use std::ptr;
/// Small helper for sending pointers which are not send.
#[repr(transparent)]
pub(crate) struct RawSend<T>(pub(crate) ptr::NonNull<T>)
where
T: ?Sized;
// Safety: this is limited to the module and guaranteed to be correct.
unsafe impl<T> Send for RawSend<T> where T: ?Sized {}
|
use rule::Rule;
#[test]
fn not_1() {
let not_this = Rule::default();
not_this.literal("not this");
let r: Rule<i32> = Rule::default();
r.literal("aaa").not(¬_this).literal("bbb").literal("ccc");
assert!(r.scan("aaabbbccc").is_ok());
assert!(r.scan("aaanot thisbbbccc").is_err());
}
#[test]
fn not_literal() {
let monkey = Rule::default();
monkey.literal("monkey");
let no_monkey: Rule<i32> = Rule::default();
no_monkey.not(&monkey);
assert!(no_monkey.scan("").is_ok());
assert!(no_monkey.scan("pizza").is_err());
assert!(no_monkey.scan("monkey").is_err());
}
#[test]
fn not_one_literal() {
let monkey = Rule::default();
monkey.literal("monkey");
let one_monkey = Rule::default();
one_monkey.one(&monkey);
let no_monkey: Rule<i32> = Rule::default();
no_monkey.not(&one_monkey);
assert!(no_monkey.scan("").is_ok());
assert!(no_monkey.scan("pizza").is_err());
assert!(no_monkey.scan("monkey").is_err());
}
#[test]
fn not_none_or_many() {
let monkey = Rule::default();
monkey.literal("monkey");
let none_or_more_monkeys = Rule::default();
none_or_more_monkeys.none_or_many(&monkey);
let no_monkeys: Rule<i32> = Rule::default();
no_monkeys.not(&none_or_more_monkeys);
assert!(no_monkeys.scan("").is_err());
assert!(no_monkeys.scan("pizza").is_err());
assert!(no_monkeys.scan("monkey").is_err());
}
#[test]
fn not_at_least_1() {
let monkey = Rule::default();
monkey.literal("monkey");
let at_least_1_monkey = Rule::default();
at_least_1_monkey.at_least(1, &monkey);
let no_monkeys: Rule<i32> = Rule::default();
no_monkeys.not(&at_least_1_monkey);
assert!(no_monkeys.scan("").is_ok());
assert!(no_monkeys.scan("pizza").is_err());
assert!(no_monkeys.scan("monkey").is_err());
}
#[test]
fn not_no_backtracks_should_be_ignored() {
let monkey = Rule::default();
monkey.literal("mon").no_backtrack("Ignore me.".to_string()).literal("key");
let gorilla = Rule::default();
gorilla.literal("gorilla");
let no_monkey: Rule<i32> = Rule::default();
no_monkey.not(&monkey).one(&gorilla);
assert_eq!(no_monkey.scan("").map_err(|x| format!("{}", x)).unwrap_err(), "Error found at line 1, column 0: Syntax error.".to_string());
assert!(no_monkey.scan("gorilla").is_ok());
assert_eq!(no_monkey.scan("monk").map_err(|x| format!("{}", x)).unwrap_err(), "Error found at line 1, column 0: Syntax error.".to_string());
assert_eq!(no_monkey.scan("monkeybananagorilla").map_err(|x| format!("{}", x)).unwrap_err(), "Error found at line 1, column 0: Syntax error.".to_string());
}
#[test]
fn nested_not_1() {
let monkey = Rule::default();
monkey.literal("monkey");
let no_monkey: Rule<i32> = Rule::default();
no_monkey.not(&monkey);
let no_no_monkey: Rule<i32> = Rule::default();
no_no_monkey.not(&no_monkey);
assert!(no_no_monkey.scan("").is_err());
assert!(no_no_monkey.scan("monkey").is_err());
let no_no_monkey_then_monkey: Rule<i32> = Rule::default();
no_no_monkey_then_monkey.one(&no_no_monkey).one(&monkey);
assert!(no_no_monkey_then_monkey.scan("monkey").is_ok());
}
#[test]
fn nested_not_2() {
let banana = Rule::default();
banana.literal("banana");
let monkey = Rule::default();
monkey.literal("monkey");
let banana_not_monkey = Rule::default();
banana_not_monkey.one(&banana).not(&monkey);
let not_banana_not_monkey: Rule<i32> = Rule::default();
not_banana_not_monkey.not(&banana_not_monkey);
assert!(not_banana_not_monkey.scan("").is_ok());
assert!(not_banana_not_monkey.scan("banana").is_err());
assert!(not_banana_not_monkey.scan("bananamonkey").is_err());
let not_banana_not_monkey_then_bananamonkey: Rule<i32> = Rule::default();
not_banana_not_monkey_then_bananamonkey.one(¬_banana_not_monkey).one(&banana).one(&monkey);
assert!(not_banana_not_monkey_then_bananamonkey.scan("bananamonkey").is_ok());
} |
fn main(){
proconio::input!{k:u64};
let mut x=0;
for i in 1..=k{
x=(x*10+7)%k;
if x ==0{
println!("{}",i);
return;
}
}
println!("-1");
}
|
pub struct Solution;
impl Solution {
pub fn add_operators(num: String, target: i32) -> Vec<String> {
if num.is_empty() {
return Vec::new();
}
let mut solver = Solver::new(num, target);
solver.solve()
}
}
#[derive(Clone, Copy)]
enum Op {
Concat,
Times,
Plus,
Minus,
}
struct Solver {
nums: Vec<i64>,
target: i64,
answers: Vec<Vec<Op>>,
}
impl Solver {
fn new(num: String, target: i32) -> Self {
Self {
nums: num.bytes().map(|b| (b - b'0') as i64).collect(),
target: target as i64,
answers: Vec::new(),
}
}
fn solve(&mut self) -> Vec<String> {
self.rec(1, 0, 1, self.nums[0], &mut Vec::new());
let mut res = Vec::new();
for ops in &self.answers {
let mut exp = Vec::new();
for i in 0..ops.len() {
exp.push(self.nums[i] as u8 + b'0');
match ops[i] {
Op::Concat => (),
Op::Times => exp.push(b'*'),
Op::Plus => exp.push(b'+'),
Op::Minus => exp.push(b'-'),
}
}
exp.push(self.nums[self.nums.len() - 1] as u8 + b'0');
res.push(String::from_utf8(exp).unwrap());
}
res
}
fn rec(&mut self, i: usize, a: i64, b: i64, c: i64, ops: &mut Vec<Op>) {
if i == self.nums.len() {
if a + b * c == self.target {
self.answers.push(ops.clone());
}
return;
}
if c != 0 {
ops.push(Op::Concat);
self.rec(i + 1, a, b, c * 10 + self.nums[i], ops);
ops.pop();
}
ops.push(Op::Times);
self.rec(i + 1, a, b * c, self.nums[i], ops);
ops.pop();
ops.push(Op::Plus);
self.rec(i + 1, a + b * c, 1, self.nums[i], ops);
ops.pop();
ops.push(Op::Minus);
self.rec(i + 1, a + b * c, -1, self.nums[i], ops);
ops.pop();
}
}
#[test]
fn test0282() {
fn case(num: &str, target: i32, want: Vec<&str>) {
let got = Solution::add_operators(num.to_string(), target);
assert_eq!(got, want);
}
case("123", 6, vec!["1*2*3", "1+2+3"]);
case("232", 8, vec!["2*3+2", "2+3*2"]);
case("105", 5, vec!["10-5", "1*0+5"]);
case("00", 0, vec!["0*0", "0+0", "0-0"]);
case("3456237490", 9191, vec![]);
case("", 5, vec![]);
}
|
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! This is not a typical test harness, because alerts require user input.
use Alert;
use AlertMethods;
use cocoa::appkit;
use core::task::PlatformThread;
use core::task;
#[main]
pub fn main() {
let mut builder = task::task();
builder.sched_mode(PlatformThread);
builder.spawn(|| {
init();
let mut alert: Alert = AlertMethods::new("All units destroyed.");
alert.add_prompt();
alert.run()
});
}
#[cfg(target_os="macos")]
fn init() {
let _ = appkit::NSApp();
}
|
pub mod units {
pub enum Units {
F,
C,
K,
Unknown,
}
} |
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use bstr::ByteSlice;
use crate::cmd::call_on_path;
use crate::error::FatalError;
pub fn is_dirty(dir: &Path) -> Result<bool, FatalError> {
let output = Command::new("git")
.arg("diff")
.arg("HEAD")
.arg("--exit-code")
.arg("--name-only")
.current_dir(dir)
.output()
.map_err(FatalError::from)?;
let tracked_unclean = !output.status.success();
let output = Command::new("git")
.arg("ls-files")
.arg("--exclude-standard")
.arg("--others")
.current_dir(dir)
.output()
.map_err(FatalError::from)?;
let untracked_files = String::from_utf8_lossy(&output.stdout);
let untracked = !untracked_files.as_ref().trim().is_empty();
Ok(tracked_unclean || untracked)
}
pub fn changed_files(dir: &Path, tag: &str) -> Result<Option<Vec<PathBuf>>, FatalError> {
let output = Command::new("git")
.arg("diff")
.arg(&format!("{}..HEAD", tag))
.arg("--name-only")
.arg("--exit-code")
.arg(".")
.current_dir(dir)
.output()
.map_err(FatalError::from)?;
match output.status.code() {
Some(0) => Ok(Some(Vec::new())),
Some(1) => {
let paths = output
.stdout
.lines()
.map(|l| dir.join(l.to_path_lossy()))
.collect();
Ok(Some(paths))
}
_ => Ok(None), // For cases like non-existent tag
}
}
pub fn commit_all(dir: &Path, msg: &str, sign: bool, dry_run: bool) -> Result<bool, FatalError> {
call_on_path(
vec!["git", "commit", if sign { "-S" } else { "" }, "-am", msg],
dir,
dry_run,
)
}
pub fn tag(
dir: &Path,
name: &str,
msg: &str,
sign: bool,
dry_run: bool,
) -> Result<bool, FatalError> {
call_on_path(
vec![
"git",
"tag",
"-a",
name,
"-m",
msg,
if sign { "-s" } else { "" },
],
dir,
dry_run,
)
}
pub fn push(dir: &Path, remote: &str, dry_run: bool) -> Result<bool, FatalError> {
call_on_path(vec!["git", "push", remote], dir, dry_run)
}
pub fn push_tag(dir: &Path, remote: &str, tag: &str, dry_run: bool) -> Result<bool, FatalError> {
call_on_path(vec!["git", "push", remote, tag], dir, dry_run)
}
pub fn top_level(dir: &Path) -> Result<PathBuf, FatalError> {
let output = Command::new("git")
.arg("rev-parse")
.arg("--show-toplevel")
.current_dir(dir)
.output()
.map_err(FatalError::from)?;
let path = std::str::from_utf8(&output.stdout)
.map_err(FatalError::from)?
.trim_end();
Ok(Path::new(path).to_owned())
}
pub(crate) fn git_version() -> Result<(), FatalError> {
Command::new("git")
.arg("--version")
.output()
.map(|_| ())
.map_err(|_| FatalError::GitError)
}
|
use std::error::Error as StdError;
use std::fmt::{Display, Formatter, Result};
use crate::parser::prelude::*;
use crate::Key;
use winnow::error::ContextError;
use winnow::error::ParseError;
/// Type representing a TOML parse error
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct TomlError {
message: String,
original: Option<String>,
keys: Vec<String>,
span: Option<std::ops::Range<usize>>,
}
impl TomlError {
pub(crate) fn new(error: ParseError<Input<'_>, ContextError>, mut original: Input<'_>) -> Self {
use winnow::stream::Stream;
let offset = error.offset();
let span = if offset == original.len() {
offset..offset
} else {
offset..(offset + 1)
};
let message = error.inner().to_string();
let original = original.finish();
Self {
message,
original: Some(
String::from_utf8(original.to_owned()).expect("original document was utf8"),
),
keys: Vec::new(),
span: Some(span),
}
}
#[cfg(feature = "serde")]
pub(crate) fn custom(message: String, span: Option<std::ops::Range<usize>>) -> Self {
Self {
message,
original: None,
keys: Vec::new(),
span,
}
}
#[cfg(feature = "serde")]
pub(crate) fn add_key(&mut self, key: String) {
self.keys.insert(0, key);
}
/// What went wrong
pub fn message(&self) -> &str {
&self.message
}
/// The start/end index into the original document where the error occurred
pub fn span(&self) -> Option<std::ops::Range<usize>> {
self.span.clone()
}
#[cfg(feature = "serde")]
pub(crate) fn set_span(&mut self, span: Option<std::ops::Range<usize>>) {
self.span = span;
}
#[cfg(feature = "serde")]
pub(crate) fn set_original(&mut self, original: Option<String>) {
self.original = original;
}
}
/// Displays a TOML parse error
///
/// # Example
///
/// TOML parse error at line 1, column 10
/// |
/// 1 | 00:32:00.a999999
/// | ^
/// Unexpected `a`
/// Expected `digit`
/// While parsing a Time
/// While parsing a Date-Time
impl Display for TomlError {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let mut context = false;
if let (Some(original), Some(span)) = (&self.original, self.span()) {
context = true;
let (line, column) = translate_position(original.as_bytes(), span.start);
let line_num = line + 1;
let col_num = column + 1;
let gutter = line_num.to_string().len();
let content = original.split('\n').nth(line).expect("valid line number");
writeln!(
f,
"TOML parse error at line {}, column {}",
line_num, col_num
)?;
// |
for _ in 0..=gutter {
write!(f, " ")?;
}
writeln!(f, "|")?;
// 1 | 00:32:00.a999999
write!(f, "{} | ", line_num)?;
writeln!(f, "{}", content)?;
// | ^
for _ in 0..=gutter {
write!(f, " ")?;
}
write!(f, "|")?;
for _ in 0..=column {
write!(f, " ")?;
}
// The span will be empty at eof, so we need to make sure we always print at least
// one `^`
write!(f, "^")?;
for _ in (span.start + 1)..(span.end.min(span.start + content.len())) {
write!(f, "^")?;
}
writeln!(f)?;
}
writeln!(f, "{}", self.message)?;
if !context && !self.keys.is_empty() {
writeln!(f, "in `{}`", self.keys.join("."))?;
}
Ok(())
}
}
impl StdError for TomlError {
fn description(&self) -> &'static str {
"TOML parse error"
}
}
fn translate_position(input: &[u8], index: usize) -> (usize, usize) {
if input.is_empty() {
return (0, index);
}
let safe_index = index.min(input.len() - 1);
let column_offset = index - safe_index;
let index = safe_index;
let nl = input[0..index]
.iter()
.rev()
.enumerate()
.find(|(_, b)| **b == b'\n')
.map(|(nl, _)| index - nl - 1);
let line_start = match nl {
Some(nl) => nl + 1,
None => 0,
};
let line = input[0..line_start].iter().filter(|b| **b == b'\n').count();
let line = line;
let column = std::str::from_utf8(&input[line_start..=index])
.map(|s| s.chars().count() - 1)
.unwrap_or_else(|_| index - line_start);
let column = column + column_offset;
(line, column)
}
#[cfg(test)]
mod test_translate_position {
use super::*;
#[test]
fn empty() {
let input = b"";
let index = 0;
let position = translate_position(&input[..], index);
assert_eq!(position, (0, 0));
}
#[test]
fn start() {
let input = b"Hello";
let index = 0;
let position = translate_position(&input[..], index);
assert_eq!(position, (0, 0));
}
#[test]
fn end() {
let input = b"Hello";
let index = input.len() - 1;
let position = translate_position(&input[..], index);
assert_eq!(position, (0, input.len() - 1));
}
#[test]
fn after() {
let input = b"Hello";
let index = input.len();
let position = translate_position(&input[..], index);
assert_eq!(position, (0, input.len()));
}
#[test]
fn first_line() {
let input = b"Hello\nWorld\n";
let index = 2;
let position = translate_position(&input[..], index);
assert_eq!(position, (0, 2));
}
#[test]
fn end_of_line() {
let input = b"Hello\nWorld\n";
let index = 5;
let position = translate_position(&input[..], index);
assert_eq!(position, (0, 5));
}
#[test]
fn start_of_second_line() {
let input = b"Hello\nWorld\n";
let index = 6;
let position = translate_position(&input[..], index);
assert_eq!(position, (1, 0));
}
#[test]
fn second_line() {
let input = b"Hello\nWorld\n";
let index = 8;
let position = translate_position(&input[..], index);
assert_eq!(position, (1, 2));
}
}
#[derive(Debug, Clone)]
pub(crate) enum CustomError {
DuplicateKey {
key: String,
table: Option<Vec<Key>>,
},
DottedKeyExtendWrongType {
key: Vec<Key>,
actual: &'static str,
},
OutOfRange,
#[cfg_attr(feature = "unbounded", allow(dead_code))]
RecursionLimitExceeded,
}
impl CustomError {
pub(crate) fn duplicate_key(path: &[Key], i: usize) -> Self {
assert!(i < path.len());
let key = &path[i];
let repr = key.display_repr();
Self::DuplicateKey {
key: repr.into(),
table: Some(path[..i].to_vec()),
}
}
pub(crate) fn extend_wrong_type(path: &[Key], i: usize, actual: &'static str) -> Self {
assert!(i < path.len());
Self::DottedKeyExtendWrongType {
key: path[..=i].to_vec(),
actual,
}
}
}
impl StdError for CustomError {
fn description(&self) -> &'static str {
"TOML parse error"
}
}
impl Display for CustomError {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
match self {
CustomError::DuplicateKey { key, table } => {
if let Some(table) = table {
if table.is_empty() {
write!(f, "duplicate key `{}` in document root", key)
} else {
let path = table.iter().map(|k| k.get()).collect::<Vec<_>>().join(".");
write!(f, "duplicate key `{}` in table `{}`", key, path)
}
} else {
write!(f, "duplicate key `{}`", key)
}
}
CustomError::DottedKeyExtendWrongType { key, actual } => {
let path = key.iter().map(|k| k.get()).collect::<Vec<_>>().join(".");
write!(
f,
"dotted key `{}` attempted to extend non-table type ({})",
path, actual
)
}
CustomError::OutOfRange => write!(f, "value is out of range"),
CustomError::RecursionLimitExceeded => write!(f, "recursion limit exceded"),
}
}
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::_0_GENA {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = "Possible values of the field `PWM_0_GENA_ACTZERO`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_0_GENA_ACTZEROR {
#[doc = "Do nothing"]
PWM_0_GENA_ACTZERO_NONE,
#[doc = "Invert pwmA"]
PWM_0_GENA_ACTZERO_INV,
#[doc = "Drive pwmA Low"]
PWM_0_GENA_ACTZERO_ZERO,
#[doc = "Drive pwmA High"]
PWM_0_GENA_ACTZERO_ONE,
}
impl PWM_0_GENA_ACTZEROR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
PWM_0_GENA_ACTZEROR::PWM_0_GENA_ACTZERO_NONE => 0,
PWM_0_GENA_ACTZEROR::PWM_0_GENA_ACTZERO_INV => 1,
PWM_0_GENA_ACTZEROR::PWM_0_GENA_ACTZERO_ZERO => 2,
PWM_0_GENA_ACTZEROR::PWM_0_GENA_ACTZERO_ONE => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> PWM_0_GENA_ACTZEROR {
match value {
0 => PWM_0_GENA_ACTZEROR::PWM_0_GENA_ACTZERO_NONE,
1 => PWM_0_GENA_ACTZEROR::PWM_0_GENA_ACTZERO_INV,
2 => PWM_0_GENA_ACTZEROR::PWM_0_GENA_ACTZERO_ZERO,
3 => PWM_0_GENA_ACTZEROR::PWM_0_GENA_ACTZERO_ONE,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTZERO_NONE`"]
#[inline(always)]
pub fn is_pwm_0_gena_actzero_none(&self) -> bool {
*self == PWM_0_GENA_ACTZEROR::PWM_0_GENA_ACTZERO_NONE
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTZERO_INV`"]
#[inline(always)]
pub fn is_pwm_0_gena_actzero_inv(&self) -> bool {
*self == PWM_0_GENA_ACTZEROR::PWM_0_GENA_ACTZERO_INV
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTZERO_ZERO`"]
#[inline(always)]
pub fn is_pwm_0_gena_actzero_zero(&self) -> bool {
*self == PWM_0_GENA_ACTZEROR::PWM_0_GENA_ACTZERO_ZERO
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTZERO_ONE`"]
#[inline(always)]
pub fn is_pwm_0_gena_actzero_one(&self) -> bool {
*self == PWM_0_GENA_ACTZEROR::PWM_0_GENA_ACTZERO_ONE
}
}
#[doc = "Values that can be written to the field `PWM_0_GENA_ACTZERO`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_0_GENA_ACTZEROW {
#[doc = "Do nothing"]
PWM_0_GENA_ACTZERO_NONE,
#[doc = "Invert pwmA"]
PWM_0_GENA_ACTZERO_INV,
#[doc = "Drive pwmA Low"]
PWM_0_GENA_ACTZERO_ZERO,
#[doc = "Drive pwmA High"]
PWM_0_GENA_ACTZERO_ONE,
}
impl PWM_0_GENA_ACTZEROW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
PWM_0_GENA_ACTZEROW::PWM_0_GENA_ACTZERO_NONE => 0,
PWM_0_GENA_ACTZEROW::PWM_0_GENA_ACTZERO_INV => 1,
PWM_0_GENA_ACTZEROW::PWM_0_GENA_ACTZERO_ZERO => 2,
PWM_0_GENA_ACTZEROW::PWM_0_GENA_ACTZERO_ONE => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _PWM_0_GENA_ACTZEROW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_0_GENA_ACTZEROW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PWM_0_GENA_ACTZEROW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Do nothing"]
#[inline(always)]
pub fn pwm_0_gena_actzero_none(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTZEROW::PWM_0_GENA_ACTZERO_NONE)
}
#[doc = "Invert pwmA"]
#[inline(always)]
pub fn pwm_0_gena_actzero_inv(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTZEROW::PWM_0_GENA_ACTZERO_INV)
}
#[doc = "Drive pwmA Low"]
#[inline(always)]
pub fn pwm_0_gena_actzero_zero(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTZEROW::PWM_0_GENA_ACTZERO_ZERO)
}
#[doc = "Drive pwmA High"]
#[inline(always)]
pub fn pwm_0_gena_actzero_one(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTZEROW::PWM_0_GENA_ACTZERO_ONE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 0);
self.w.bits |= ((value as u32) & 3) << 0;
self.w
}
}
#[doc = "Possible values of the field `PWM_0_GENA_ACTLOAD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_0_GENA_ACTLOADR {
#[doc = "Do nothing"]
PWM_0_GENA_ACTLOAD_NONE,
#[doc = "Invert pwmA"]
PWM_0_GENA_ACTLOAD_INV,
#[doc = "Drive pwmA Low"]
PWM_0_GENA_ACTLOAD_ZERO,
#[doc = "Drive pwmA High"]
PWM_0_GENA_ACTLOAD_ONE,
}
impl PWM_0_GENA_ACTLOADR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
PWM_0_GENA_ACTLOADR::PWM_0_GENA_ACTLOAD_NONE => 0,
PWM_0_GENA_ACTLOADR::PWM_0_GENA_ACTLOAD_INV => 1,
PWM_0_GENA_ACTLOADR::PWM_0_GENA_ACTLOAD_ZERO => 2,
PWM_0_GENA_ACTLOADR::PWM_0_GENA_ACTLOAD_ONE => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> PWM_0_GENA_ACTLOADR {
match value {
0 => PWM_0_GENA_ACTLOADR::PWM_0_GENA_ACTLOAD_NONE,
1 => PWM_0_GENA_ACTLOADR::PWM_0_GENA_ACTLOAD_INV,
2 => PWM_0_GENA_ACTLOADR::PWM_0_GENA_ACTLOAD_ZERO,
3 => PWM_0_GENA_ACTLOADR::PWM_0_GENA_ACTLOAD_ONE,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTLOAD_NONE`"]
#[inline(always)]
pub fn is_pwm_0_gena_actload_none(&self) -> bool {
*self == PWM_0_GENA_ACTLOADR::PWM_0_GENA_ACTLOAD_NONE
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTLOAD_INV`"]
#[inline(always)]
pub fn is_pwm_0_gena_actload_inv(&self) -> bool {
*self == PWM_0_GENA_ACTLOADR::PWM_0_GENA_ACTLOAD_INV
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTLOAD_ZERO`"]
#[inline(always)]
pub fn is_pwm_0_gena_actload_zero(&self) -> bool {
*self == PWM_0_GENA_ACTLOADR::PWM_0_GENA_ACTLOAD_ZERO
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTLOAD_ONE`"]
#[inline(always)]
pub fn is_pwm_0_gena_actload_one(&self) -> bool {
*self == PWM_0_GENA_ACTLOADR::PWM_0_GENA_ACTLOAD_ONE
}
}
#[doc = "Values that can be written to the field `PWM_0_GENA_ACTLOAD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_0_GENA_ACTLOADW {
#[doc = "Do nothing"]
PWM_0_GENA_ACTLOAD_NONE,
#[doc = "Invert pwmA"]
PWM_0_GENA_ACTLOAD_INV,
#[doc = "Drive pwmA Low"]
PWM_0_GENA_ACTLOAD_ZERO,
#[doc = "Drive pwmA High"]
PWM_0_GENA_ACTLOAD_ONE,
}
impl PWM_0_GENA_ACTLOADW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
PWM_0_GENA_ACTLOADW::PWM_0_GENA_ACTLOAD_NONE => 0,
PWM_0_GENA_ACTLOADW::PWM_0_GENA_ACTLOAD_INV => 1,
PWM_0_GENA_ACTLOADW::PWM_0_GENA_ACTLOAD_ZERO => 2,
PWM_0_GENA_ACTLOADW::PWM_0_GENA_ACTLOAD_ONE => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _PWM_0_GENA_ACTLOADW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_0_GENA_ACTLOADW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PWM_0_GENA_ACTLOADW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Do nothing"]
#[inline(always)]
pub fn pwm_0_gena_actload_none(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTLOADW::PWM_0_GENA_ACTLOAD_NONE)
}
#[doc = "Invert pwmA"]
#[inline(always)]
pub fn pwm_0_gena_actload_inv(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTLOADW::PWM_0_GENA_ACTLOAD_INV)
}
#[doc = "Drive pwmA Low"]
#[inline(always)]
pub fn pwm_0_gena_actload_zero(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTLOADW::PWM_0_GENA_ACTLOAD_ZERO)
}
#[doc = "Drive pwmA High"]
#[inline(always)]
pub fn pwm_0_gena_actload_one(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTLOADW::PWM_0_GENA_ACTLOAD_ONE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 2);
self.w.bits |= ((value as u32) & 3) << 2;
self.w
}
}
#[doc = "Possible values of the field `PWM_0_GENA_ACTCMPAU`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_0_GENA_ACTCMPAUR {
#[doc = "Do nothing"]
PWM_0_GENA_ACTCMPAU_NONE,
#[doc = "Invert pwmA"]
PWM_0_GENA_ACTCMPAU_INV,
#[doc = "Drive pwmA Low"]
PWM_0_GENA_ACTCMPAU_ZERO,
#[doc = "Drive pwmA High"]
PWM_0_GENA_ACTCMPAU_ONE,
}
impl PWM_0_GENA_ACTCMPAUR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
PWM_0_GENA_ACTCMPAUR::PWM_0_GENA_ACTCMPAU_NONE => 0,
PWM_0_GENA_ACTCMPAUR::PWM_0_GENA_ACTCMPAU_INV => 1,
PWM_0_GENA_ACTCMPAUR::PWM_0_GENA_ACTCMPAU_ZERO => 2,
PWM_0_GENA_ACTCMPAUR::PWM_0_GENA_ACTCMPAU_ONE => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> PWM_0_GENA_ACTCMPAUR {
match value {
0 => PWM_0_GENA_ACTCMPAUR::PWM_0_GENA_ACTCMPAU_NONE,
1 => PWM_0_GENA_ACTCMPAUR::PWM_0_GENA_ACTCMPAU_INV,
2 => PWM_0_GENA_ACTCMPAUR::PWM_0_GENA_ACTCMPAU_ZERO,
3 => PWM_0_GENA_ACTCMPAUR::PWM_0_GENA_ACTCMPAU_ONE,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTCMPAU_NONE`"]
#[inline(always)]
pub fn is_pwm_0_gena_actcmpau_none(&self) -> bool {
*self == PWM_0_GENA_ACTCMPAUR::PWM_0_GENA_ACTCMPAU_NONE
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTCMPAU_INV`"]
#[inline(always)]
pub fn is_pwm_0_gena_actcmpau_inv(&self) -> bool {
*self == PWM_0_GENA_ACTCMPAUR::PWM_0_GENA_ACTCMPAU_INV
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTCMPAU_ZERO`"]
#[inline(always)]
pub fn is_pwm_0_gena_actcmpau_zero(&self) -> bool {
*self == PWM_0_GENA_ACTCMPAUR::PWM_0_GENA_ACTCMPAU_ZERO
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTCMPAU_ONE`"]
#[inline(always)]
pub fn is_pwm_0_gena_actcmpau_one(&self) -> bool {
*self == PWM_0_GENA_ACTCMPAUR::PWM_0_GENA_ACTCMPAU_ONE
}
}
#[doc = "Values that can be written to the field `PWM_0_GENA_ACTCMPAU`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_0_GENA_ACTCMPAUW {
#[doc = "Do nothing"]
PWM_0_GENA_ACTCMPAU_NONE,
#[doc = "Invert pwmA"]
PWM_0_GENA_ACTCMPAU_INV,
#[doc = "Drive pwmA Low"]
PWM_0_GENA_ACTCMPAU_ZERO,
#[doc = "Drive pwmA High"]
PWM_0_GENA_ACTCMPAU_ONE,
}
impl PWM_0_GENA_ACTCMPAUW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
PWM_0_GENA_ACTCMPAUW::PWM_0_GENA_ACTCMPAU_NONE => 0,
PWM_0_GENA_ACTCMPAUW::PWM_0_GENA_ACTCMPAU_INV => 1,
PWM_0_GENA_ACTCMPAUW::PWM_0_GENA_ACTCMPAU_ZERO => 2,
PWM_0_GENA_ACTCMPAUW::PWM_0_GENA_ACTCMPAU_ONE => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _PWM_0_GENA_ACTCMPAUW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_0_GENA_ACTCMPAUW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PWM_0_GENA_ACTCMPAUW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Do nothing"]
#[inline(always)]
pub fn pwm_0_gena_actcmpau_none(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTCMPAUW::PWM_0_GENA_ACTCMPAU_NONE)
}
#[doc = "Invert pwmA"]
#[inline(always)]
pub fn pwm_0_gena_actcmpau_inv(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTCMPAUW::PWM_0_GENA_ACTCMPAU_INV)
}
#[doc = "Drive pwmA Low"]
#[inline(always)]
pub fn pwm_0_gena_actcmpau_zero(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTCMPAUW::PWM_0_GENA_ACTCMPAU_ZERO)
}
#[doc = "Drive pwmA High"]
#[inline(always)]
pub fn pwm_0_gena_actcmpau_one(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTCMPAUW::PWM_0_GENA_ACTCMPAU_ONE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 4);
self.w.bits |= ((value as u32) & 3) << 4;
self.w
}
}
#[doc = "Possible values of the field `PWM_0_GENA_ACTCMPAD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_0_GENA_ACTCMPADR {
#[doc = "Do nothing"]
PWM_0_GENA_ACTCMPAD_NONE,
#[doc = "Invert pwmA"]
PWM_0_GENA_ACTCMPAD_INV,
#[doc = "Drive pwmA Low"]
PWM_0_GENA_ACTCMPAD_ZERO,
#[doc = "Drive pwmA High"]
PWM_0_GENA_ACTCMPAD_ONE,
}
impl PWM_0_GENA_ACTCMPADR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
PWM_0_GENA_ACTCMPADR::PWM_0_GENA_ACTCMPAD_NONE => 0,
PWM_0_GENA_ACTCMPADR::PWM_0_GENA_ACTCMPAD_INV => 1,
PWM_0_GENA_ACTCMPADR::PWM_0_GENA_ACTCMPAD_ZERO => 2,
PWM_0_GENA_ACTCMPADR::PWM_0_GENA_ACTCMPAD_ONE => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> PWM_0_GENA_ACTCMPADR {
match value {
0 => PWM_0_GENA_ACTCMPADR::PWM_0_GENA_ACTCMPAD_NONE,
1 => PWM_0_GENA_ACTCMPADR::PWM_0_GENA_ACTCMPAD_INV,
2 => PWM_0_GENA_ACTCMPADR::PWM_0_GENA_ACTCMPAD_ZERO,
3 => PWM_0_GENA_ACTCMPADR::PWM_0_GENA_ACTCMPAD_ONE,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTCMPAD_NONE`"]
#[inline(always)]
pub fn is_pwm_0_gena_actcmpad_none(&self) -> bool {
*self == PWM_0_GENA_ACTCMPADR::PWM_0_GENA_ACTCMPAD_NONE
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTCMPAD_INV`"]
#[inline(always)]
pub fn is_pwm_0_gena_actcmpad_inv(&self) -> bool {
*self == PWM_0_GENA_ACTCMPADR::PWM_0_GENA_ACTCMPAD_INV
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTCMPAD_ZERO`"]
#[inline(always)]
pub fn is_pwm_0_gena_actcmpad_zero(&self) -> bool {
*self == PWM_0_GENA_ACTCMPADR::PWM_0_GENA_ACTCMPAD_ZERO
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTCMPAD_ONE`"]
#[inline(always)]
pub fn is_pwm_0_gena_actcmpad_one(&self) -> bool {
*self == PWM_0_GENA_ACTCMPADR::PWM_0_GENA_ACTCMPAD_ONE
}
}
#[doc = "Values that can be written to the field `PWM_0_GENA_ACTCMPAD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_0_GENA_ACTCMPADW {
#[doc = "Do nothing"]
PWM_0_GENA_ACTCMPAD_NONE,
#[doc = "Invert pwmA"]
PWM_0_GENA_ACTCMPAD_INV,
#[doc = "Drive pwmA Low"]
PWM_0_GENA_ACTCMPAD_ZERO,
#[doc = "Drive pwmA High"]
PWM_0_GENA_ACTCMPAD_ONE,
}
impl PWM_0_GENA_ACTCMPADW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
PWM_0_GENA_ACTCMPADW::PWM_0_GENA_ACTCMPAD_NONE => 0,
PWM_0_GENA_ACTCMPADW::PWM_0_GENA_ACTCMPAD_INV => 1,
PWM_0_GENA_ACTCMPADW::PWM_0_GENA_ACTCMPAD_ZERO => 2,
PWM_0_GENA_ACTCMPADW::PWM_0_GENA_ACTCMPAD_ONE => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _PWM_0_GENA_ACTCMPADW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_0_GENA_ACTCMPADW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PWM_0_GENA_ACTCMPADW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Do nothing"]
#[inline(always)]
pub fn pwm_0_gena_actcmpad_none(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTCMPADW::PWM_0_GENA_ACTCMPAD_NONE)
}
#[doc = "Invert pwmA"]
#[inline(always)]
pub fn pwm_0_gena_actcmpad_inv(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTCMPADW::PWM_0_GENA_ACTCMPAD_INV)
}
#[doc = "Drive pwmA Low"]
#[inline(always)]
pub fn pwm_0_gena_actcmpad_zero(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTCMPADW::PWM_0_GENA_ACTCMPAD_ZERO)
}
#[doc = "Drive pwmA High"]
#[inline(always)]
pub fn pwm_0_gena_actcmpad_one(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTCMPADW::PWM_0_GENA_ACTCMPAD_ONE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 6);
self.w.bits |= ((value as u32) & 3) << 6;
self.w
}
}
#[doc = "Possible values of the field `PWM_0_GENA_ACTCMPBU`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_0_GENA_ACTCMPBUR {
#[doc = "Do nothing"]
PWM_0_GENA_ACTCMPBU_NONE,
#[doc = "Invert pwmA"]
PWM_0_GENA_ACTCMPBU_INV,
#[doc = "Drive pwmA Low"]
PWM_0_GENA_ACTCMPBU_ZERO,
#[doc = "Drive pwmA High"]
PWM_0_GENA_ACTCMPBU_ONE,
}
impl PWM_0_GENA_ACTCMPBUR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
PWM_0_GENA_ACTCMPBUR::PWM_0_GENA_ACTCMPBU_NONE => 0,
PWM_0_GENA_ACTCMPBUR::PWM_0_GENA_ACTCMPBU_INV => 1,
PWM_0_GENA_ACTCMPBUR::PWM_0_GENA_ACTCMPBU_ZERO => 2,
PWM_0_GENA_ACTCMPBUR::PWM_0_GENA_ACTCMPBU_ONE => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> PWM_0_GENA_ACTCMPBUR {
match value {
0 => PWM_0_GENA_ACTCMPBUR::PWM_0_GENA_ACTCMPBU_NONE,
1 => PWM_0_GENA_ACTCMPBUR::PWM_0_GENA_ACTCMPBU_INV,
2 => PWM_0_GENA_ACTCMPBUR::PWM_0_GENA_ACTCMPBU_ZERO,
3 => PWM_0_GENA_ACTCMPBUR::PWM_0_GENA_ACTCMPBU_ONE,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTCMPBU_NONE`"]
#[inline(always)]
pub fn is_pwm_0_gena_actcmpbu_none(&self) -> bool {
*self == PWM_0_GENA_ACTCMPBUR::PWM_0_GENA_ACTCMPBU_NONE
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTCMPBU_INV`"]
#[inline(always)]
pub fn is_pwm_0_gena_actcmpbu_inv(&self) -> bool {
*self == PWM_0_GENA_ACTCMPBUR::PWM_0_GENA_ACTCMPBU_INV
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTCMPBU_ZERO`"]
#[inline(always)]
pub fn is_pwm_0_gena_actcmpbu_zero(&self) -> bool {
*self == PWM_0_GENA_ACTCMPBUR::PWM_0_GENA_ACTCMPBU_ZERO
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTCMPBU_ONE`"]
#[inline(always)]
pub fn is_pwm_0_gena_actcmpbu_one(&self) -> bool {
*self == PWM_0_GENA_ACTCMPBUR::PWM_0_GENA_ACTCMPBU_ONE
}
}
#[doc = "Values that can be written to the field `PWM_0_GENA_ACTCMPBU`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_0_GENA_ACTCMPBUW {
#[doc = "Do nothing"]
PWM_0_GENA_ACTCMPBU_NONE,
#[doc = "Invert pwmA"]
PWM_0_GENA_ACTCMPBU_INV,
#[doc = "Drive pwmA Low"]
PWM_0_GENA_ACTCMPBU_ZERO,
#[doc = "Drive pwmA High"]
PWM_0_GENA_ACTCMPBU_ONE,
}
impl PWM_0_GENA_ACTCMPBUW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
PWM_0_GENA_ACTCMPBUW::PWM_0_GENA_ACTCMPBU_NONE => 0,
PWM_0_GENA_ACTCMPBUW::PWM_0_GENA_ACTCMPBU_INV => 1,
PWM_0_GENA_ACTCMPBUW::PWM_0_GENA_ACTCMPBU_ZERO => 2,
PWM_0_GENA_ACTCMPBUW::PWM_0_GENA_ACTCMPBU_ONE => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _PWM_0_GENA_ACTCMPBUW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_0_GENA_ACTCMPBUW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PWM_0_GENA_ACTCMPBUW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Do nothing"]
#[inline(always)]
pub fn pwm_0_gena_actcmpbu_none(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTCMPBUW::PWM_0_GENA_ACTCMPBU_NONE)
}
#[doc = "Invert pwmA"]
#[inline(always)]
pub fn pwm_0_gena_actcmpbu_inv(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTCMPBUW::PWM_0_GENA_ACTCMPBU_INV)
}
#[doc = "Drive pwmA Low"]
#[inline(always)]
pub fn pwm_0_gena_actcmpbu_zero(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTCMPBUW::PWM_0_GENA_ACTCMPBU_ZERO)
}
#[doc = "Drive pwmA High"]
#[inline(always)]
pub fn pwm_0_gena_actcmpbu_one(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTCMPBUW::PWM_0_GENA_ACTCMPBU_ONE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 8);
self.w.bits |= ((value as u32) & 3) << 8;
self.w
}
}
#[doc = "Possible values of the field `PWM_0_GENA_ACTCMPBD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_0_GENA_ACTCMPBDR {
#[doc = "Do nothing"]
PWM_0_GENA_ACTCMPBD_NONE,
#[doc = "Invert pwmA"]
PWM_0_GENA_ACTCMPBD_INV,
#[doc = "Drive pwmA Low"]
PWM_0_GENA_ACTCMPBD_ZERO,
#[doc = "Drive pwmA High"]
PWM_0_GENA_ACTCMPBD_ONE,
}
impl PWM_0_GENA_ACTCMPBDR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
PWM_0_GENA_ACTCMPBDR::PWM_0_GENA_ACTCMPBD_NONE => 0,
PWM_0_GENA_ACTCMPBDR::PWM_0_GENA_ACTCMPBD_INV => 1,
PWM_0_GENA_ACTCMPBDR::PWM_0_GENA_ACTCMPBD_ZERO => 2,
PWM_0_GENA_ACTCMPBDR::PWM_0_GENA_ACTCMPBD_ONE => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> PWM_0_GENA_ACTCMPBDR {
match value {
0 => PWM_0_GENA_ACTCMPBDR::PWM_0_GENA_ACTCMPBD_NONE,
1 => PWM_0_GENA_ACTCMPBDR::PWM_0_GENA_ACTCMPBD_INV,
2 => PWM_0_GENA_ACTCMPBDR::PWM_0_GENA_ACTCMPBD_ZERO,
3 => PWM_0_GENA_ACTCMPBDR::PWM_0_GENA_ACTCMPBD_ONE,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTCMPBD_NONE`"]
#[inline(always)]
pub fn is_pwm_0_gena_actcmpbd_none(&self) -> bool {
*self == PWM_0_GENA_ACTCMPBDR::PWM_0_GENA_ACTCMPBD_NONE
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTCMPBD_INV`"]
#[inline(always)]
pub fn is_pwm_0_gena_actcmpbd_inv(&self) -> bool {
*self == PWM_0_GENA_ACTCMPBDR::PWM_0_GENA_ACTCMPBD_INV
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTCMPBD_ZERO`"]
#[inline(always)]
pub fn is_pwm_0_gena_actcmpbd_zero(&self) -> bool {
*self == PWM_0_GENA_ACTCMPBDR::PWM_0_GENA_ACTCMPBD_ZERO
}
#[doc = "Checks if the value of the field is `PWM_0_GENA_ACTCMPBD_ONE`"]
#[inline(always)]
pub fn is_pwm_0_gena_actcmpbd_one(&self) -> bool {
*self == PWM_0_GENA_ACTCMPBDR::PWM_0_GENA_ACTCMPBD_ONE
}
}
#[doc = "Values that can be written to the field `PWM_0_GENA_ACTCMPBD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PWM_0_GENA_ACTCMPBDW {
#[doc = "Do nothing"]
PWM_0_GENA_ACTCMPBD_NONE,
#[doc = "Invert pwmA"]
PWM_0_GENA_ACTCMPBD_INV,
#[doc = "Drive pwmA Low"]
PWM_0_GENA_ACTCMPBD_ZERO,
#[doc = "Drive pwmA High"]
PWM_0_GENA_ACTCMPBD_ONE,
}
impl PWM_0_GENA_ACTCMPBDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
PWM_0_GENA_ACTCMPBDW::PWM_0_GENA_ACTCMPBD_NONE => 0,
PWM_0_GENA_ACTCMPBDW::PWM_0_GENA_ACTCMPBD_INV => 1,
PWM_0_GENA_ACTCMPBDW::PWM_0_GENA_ACTCMPBD_ZERO => 2,
PWM_0_GENA_ACTCMPBDW::PWM_0_GENA_ACTCMPBD_ONE => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _PWM_0_GENA_ACTCMPBDW<'a> {
w: &'a mut W,
}
impl<'a> _PWM_0_GENA_ACTCMPBDW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: PWM_0_GENA_ACTCMPBDW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Do nothing"]
#[inline(always)]
pub fn pwm_0_gena_actcmpbd_none(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTCMPBDW::PWM_0_GENA_ACTCMPBD_NONE)
}
#[doc = "Invert pwmA"]
#[inline(always)]
pub fn pwm_0_gena_actcmpbd_inv(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTCMPBDW::PWM_0_GENA_ACTCMPBD_INV)
}
#[doc = "Drive pwmA Low"]
#[inline(always)]
pub fn pwm_0_gena_actcmpbd_zero(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTCMPBDW::PWM_0_GENA_ACTCMPBD_ZERO)
}
#[doc = "Drive pwmA High"]
#[inline(always)]
pub fn pwm_0_gena_actcmpbd_one(self) -> &'a mut W {
self.variant(PWM_0_GENA_ACTCMPBDW::PWM_0_GENA_ACTCMPBD_ONE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 10);
self.w.bits |= ((value as u32) & 3) << 10;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:1 - Action for Counter=0"]
#[inline(always)]
pub fn pwm_0_gena_actzero(&self) -> PWM_0_GENA_ACTZEROR {
PWM_0_GENA_ACTZEROR::_from(((self.bits >> 0) & 3) as u8)
}
#[doc = "Bits 2:3 - Action for Counter=LOAD"]
#[inline(always)]
pub fn pwm_0_gena_actload(&self) -> PWM_0_GENA_ACTLOADR {
PWM_0_GENA_ACTLOADR::_from(((self.bits >> 2) & 3) as u8)
}
#[doc = "Bits 4:5 - Action for Comparator A Up"]
#[inline(always)]
pub fn pwm_0_gena_actcmpau(&self) -> PWM_0_GENA_ACTCMPAUR {
PWM_0_GENA_ACTCMPAUR::_from(((self.bits >> 4) & 3) as u8)
}
#[doc = "Bits 6:7 - Action for Comparator A Down"]
#[inline(always)]
pub fn pwm_0_gena_actcmpad(&self) -> PWM_0_GENA_ACTCMPADR {
PWM_0_GENA_ACTCMPADR::_from(((self.bits >> 6) & 3) as u8)
}
#[doc = "Bits 8:9 - Action for Comparator B Up"]
#[inline(always)]
pub fn pwm_0_gena_actcmpbu(&self) -> PWM_0_GENA_ACTCMPBUR {
PWM_0_GENA_ACTCMPBUR::_from(((self.bits >> 8) & 3) as u8)
}
#[doc = "Bits 10:11 - Action for Comparator B Down"]
#[inline(always)]
pub fn pwm_0_gena_actcmpbd(&self) -> PWM_0_GENA_ACTCMPBDR {
PWM_0_GENA_ACTCMPBDR::_from(((self.bits >> 10) & 3) as u8)
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:1 - Action for Counter=0"]
#[inline(always)]
pub fn pwm_0_gena_actzero(&mut self) -> _PWM_0_GENA_ACTZEROW {
_PWM_0_GENA_ACTZEROW { w: self }
}
#[doc = "Bits 2:3 - Action for Counter=LOAD"]
#[inline(always)]
pub fn pwm_0_gena_actload(&mut self) -> _PWM_0_GENA_ACTLOADW {
_PWM_0_GENA_ACTLOADW { w: self }
}
#[doc = "Bits 4:5 - Action for Comparator A Up"]
#[inline(always)]
pub fn pwm_0_gena_actcmpau(&mut self) -> _PWM_0_GENA_ACTCMPAUW {
_PWM_0_GENA_ACTCMPAUW { w: self }
}
#[doc = "Bits 6:7 - Action for Comparator A Down"]
#[inline(always)]
pub fn pwm_0_gena_actcmpad(&mut self) -> _PWM_0_GENA_ACTCMPADW {
_PWM_0_GENA_ACTCMPADW { w: self }
}
#[doc = "Bits 8:9 - Action for Comparator B Up"]
#[inline(always)]
pub fn pwm_0_gena_actcmpbu(&mut self) -> _PWM_0_GENA_ACTCMPBUW {
_PWM_0_GENA_ACTCMPBUW { w: self }
}
#[doc = "Bits 10:11 - Action for Comparator B Down"]
#[inline(always)]
pub fn pwm_0_gena_actcmpbd(&mut self) -> _PWM_0_GENA_ACTCMPBDW {
_PWM_0_GENA_ACTCMPBDW { w: self }
}
}
|
/// The balance of an account
#[derive(
Clone,
Debug,
Eq,
Ord,
PartialEq,
PartialOrd,
parity_scale_codec::Decode,
parity_scale_codec::Encode,
)]
pub struct AccountRate<A, B> {
account: A,
rate: B,
}
impl<A, B> AccountRate<A, B> {
/// Creates a new instance from `account` and `rate`.
#[inline]
pub fn new(account: A, rate: B) -> Self {
Self { account, rate }
}
/// Account
#[inline]
pub const fn account(&self) -> &A {
&self.account
}
/// Rate
#[inline]
pub const fn rate(&self) -> &B {
&self.rate
}
/// Mutable rate
#[inline]
pub fn rate_mut(&mut self) -> &mut B {
&mut self.rate
}
}
|
#[doc = "Reader of register SETUP_EV_PENDING"]
pub type R = crate::R<u8, super::SETUP_EV_PENDING>;
#[doc = "Writer for register SETUP_EV_PENDING"]
pub type W = crate::W<u8, super::SETUP_EV_PENDING>;
#[doc = "Register SETUP_EV_PENDING `reset()`'s with value 0"]
impl crate::ResetValue for super::SETUP_EV_PENDING {
type Type = u8;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `setup_ev_pending`"]
pub type SETUP_EV_PENDING_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `setup_ev_pending`"]
pub struct SETUP_EV_PENDING_W<'a> {
w: &'a mut W,
}
impl<'a> SETUP_EV_PENDING_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x03) | ((value as u8) & 0x03);
self.w
}
}
impl R {
#[doc = "Bits 0:1"]
#[inline(always)]
pub fn setup_ev_pending(&self) -> SETUP_EV_PENDING_R {
SETUP_EV_PENDING_R::new((self.bits & 0x03) as u8)
}
}
impl W {
#[doc = "Bits 0:1"]
#[inline(always)]
pub fn setup_ev_pending(&mut self) -> SETUP_EV_PENDING_W {
SETUP_EV_PENDING_W { w: self }
}
}
|
use anyhow::{Context, Result};
use async_std::io::{Read, Write};
use async_std::net::{TcpListener, TcpStream};
use async_trait::async_trait;
#[async_trait]
pub trait GenericListener: Sync + Send {
async fn accept<'a>(&'a self) -> Result<Socket>;
}
#[async_trait]
impl GenericListener for TcpListener {
async fn accept<'a>(&'a self) -> Result<Socket> {
let (socket, _) = self.accept().await?;
Ok(Box::new(socket))
}
}
pub trait GenericSocket: Read + Write + Unpin + Send + Sync {}
impl GenericSocket for TcpStream {}
pub type Listener = Box<dyn GenericListener>;
pub type Socket = Box<dyn GenericSocket>;
pub async fn get_client(_unix_socket_path: Option<String>, port: Option<String>) -> Result<Socket> {
// Don't allow anything else than loopback until we have proper crypto
let address = format!("127.0.0.1:{}", port.unwrap());
// Connect to socket
let socket = TcpStream::connect(&address)
.await
.context("Failed to connect to the daemon. Did you start it?")?;
Ok(Box::new(socket))
}
pub async fn get_listener(
_unix_socket_path: Option<String>,
port: Option<String>,
) -> Result<Listener> {
let port = port.unwrap();
let address = format!("127.0.0.1:{}", port);
Ok(Box::new(TcpListener::bind(address).await?))
}
|
use std::{
fs::File,
io::{BufReader, BufWriter},
};
use matrix_sdk::{
events::{room::message::MessageEventContent, AnyMessageEventContent},
Client, ClientConfig, Session, SyncSettings,
};
use systemd::{journal, JournalRecord};
use crate::autojoin::AutoJoinHandler;
use crate::Config;
#[derive(Clone)]
pub struct BadNewsBot {
client: Client,
config: Config,
}
impl BadNewsBot {
/// Creates a new [`BadNewsBot`] and builds a [`matrix_sdk::Client`] using the provided
/// [`Config`].
///
/// The [`Client`] is only initialized, not ready to be used yet.
pub fn new(config: Config) -> anyhow::Result<Self> {
let client_config = ClientConfig::new().store_path(config.state_dir.join("store"));
let client = Client::new_with_config(config.homeserver.clone(), client_config)?;
Ok(Self { client, config })
}
/// Loads session information from file, or creates it if no previous session is found.
///
/// The bot is ready to run once this function has been called.
pub async fn init(&self) -> anyhow::Result<()> {
load_or_init_session(&self).await?;
self.client
.set_event_handler(Box::new(AutoJoinHandler::new(
self.client.clone(),
self.config.room_id.clone(),
)))
.await;
Ok(())
}
/// Start listening to Matrix events.
///
/// [`BadNewsBot::init`] **must** be called before this function, otherwise the [`Client`] isn't
/// logged in.
pub async fn run(&self) {
let clone = self.clone();
tokio::task::spawn_blocking(move || clone.watch_journald());
self.client.sync(SyncSettings::default()).await
}
fn watch_journald(&self) {
let mut reader = journal::OpenOptions::default()
.system(true)
.open()
.expect("Could not open journal");
// Seek to end of current log to prevent old messages from being printed
reader
.seek_tail()
.expect("Could not seek to end of journal");
// HACK: for some reason calling `seek_tail` above still leaves old entries when calling
// next, so skip all those before we start the real logging
loop {
if reader.next().unwrap() == 0 {
break;
}
}
// NOTE: Ugly double loop, but low level `wait` has to be used if we don't want to miss any
// new entry. See https://github.com/jmesmon/rust-systemd/issues/66
loop {
loop {
let record = reader.next_entry().unwrap();
match record {
Some(record) => self.handle_record(record),
None => break,
}
}
reader.wait(None).unwrap();
}
}
fn handle_record(&self, record: JournalRecord) {
const KEY_UNIT: &str = "_SYSTEMD_UNIT";
const KEY_MESSAGE: &str = "MESSAGE";
if let Some(unit) = record.get(KEY_UNIT) {
let unit_config = match self.config.units.iter().find(|u| &u.name == unit) {
Some(config) => config,
None => return,
};
let message = match record.get(KEY_MESSAGE) {
Some(msg) => msg,
None => return,
};
if let Some(filter) = &unit_config.filter {
if !filter.is_match(message) {
return;
}
}
let message = format!(
"[{}] {}",
unit.strip_suffix(".service").unwrap_or(unit),
message,
);
let content =
AnyMessageEventContent::RoomMessage(MessageEventContent::text_plain(message));
let room_id = self.config.room_id.clone();
let client_clone = self.client.clone();
tokio::spawn(async move {
client_clone
.room_send(&room_id, content, None)
.await
.unwrap();
});
}
}
}
/// This loads the session information from an existing file, and tries to login with it. If no such
/// file is found, then login using username and password, and save the new session information on
/// disk.
async fn load_or_init_session(bot: &BadNewsBot) -> anyhow::Result<()> {
let session_file = bot.config.state_dir.join("session.yaml");
if session_file.is_file() {
let reader = BufReader::new(File::open(session_file)?);
let session: Session = serde_yaml::from_reader(reader)?;
bot.client.restore_login(session.clone()).await?;
println!("Reused session: {}, {}", session.user_id, session.device_id);
} else {
let response = bot
.client
.login(
&bot.config.username,
&bot.config.password,
None,
Some("autojoin bot"),
)
.await?;
println!("logged in as {}", bot.config.username);
let session = Session {
access_token: response.access_token,
user_id: response.user_id,
device_id: response.device_id,
};
let writer = BufWriter::new(File::create(session_file)?);
serde_yaml::to_writer(writer, &session)?;
}
Ok(())
}
|
use super::gl_render::Texture as Texture;
use super::sprite::mipmapped_texture_from_path;
use std::rc::Rc;
pub struct Textures {
pub tank_texture:Rc<Texture>,
pub turret_texture:Rc<Texture>,
pub enemy_tank_texture:Rc<Texture>,
pub enemy_turret_texture:Rc<Texture>,
pub bullet_texture:Rc<Texture>,
}
pub fn load_textures() -> Textures {
let tank_texture = mipmapped_texture_from_path("assets/Hull_A_01.png");
let enemy_tank_texture = mipmapped_texture_from_path("assets/Hull_B_01.png");
let turret_texture = mipmapped_texture_from_path("assets/Gun_A_01.png");
let enemy_turret_texture = mipmapped_texture_from_path("assets/Gun_B_01.png");
let bullet_texture = mipmapped_texture_from_path("assets/Light_Shell.png");
Textures {
tank_texture:Rc::new(tank_texture),
turret_texture:Rc::new(turret_texture),
enemy_tank_texture:Rc::new(enemy_tank_texture),
enemy_turret_texture:Rc::new(enemy_turret_texture),
bullet_texture:Rc::new(bullet_texture),
}
} |
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:helper.rs
// no-prefer-dynamic
#![feature(allocator_api)]
extern crate helper;
use std::alloc::{self, Global, Alloc, System, Layout};
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
static HITS: AtomicUsize = ATOMIC_USIZE_INIT;
struct A;
unsafe impl alloc::GlobalAlloc for A {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
HITS.fetch_add(1, Ordering::SeqCst);
System.alloc(layout)
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
HITS.fetch_add(1, Ordering::SeqCst);
System.dealloc(ptr, layout)
}
}
#[global_allocator]
static GLOBAL: A = A;
fn main() {
println!("hello!");
let n = HITS.load(Ordering::SeqCst);
assert!(n > 0);
unsafe {
let layout = Layout::from_size_align(4, 2).unwrap();
let ptr = Global.alloc(layout.clone()).unwrap();
helper::work_with(&ptr);
assert_eq!(HITS.load(Ordering::SeqCst), n + 1);
Global.dealloc(ptr, layout.clone());
assert_eq!(HITS.load(Ordering::SeqCst), n + 2);
let s = String::with_capacity(10);
helper::work_with(&s);
assert_eq!(HITS.load(Ordering::SeqCst), n + 3);
drop(s);
assert_eq!(HITS.load(Ordering::SeqCst), n + 4);
let ptr = System.alloc(layout.clone()).unwrap();
assert_eq!(HITS.load(Ordering::SeqCst), n + 4);
helper::work_with(&ptr);
System.dealloc(ptr, layout);
assert_eq!(HITS.load(Ordering::SeqCst), n + 4);
}
}
|
use csv::ReaderBuilder;
use std::{error::Error, fs::File};
pub type MyResult<T> = Result<T, Box<dyn Error>>;
#[derive(Debug)]
pub struct Config {
pub files: Vec<String>,
pub delimiter: u8,
pub has_headers: bool,
}
// --------------------------------------------------
pub fn process(
filename: &String,
delimiter: &u8,
has_headers: bool,
) -> MyResult<()> {
match File::open(filename) {
Ok(file) => {
println!("Processing {}", filename);
let mut reader = ReaderBuilder::new()
.delimiter(*delimiter)
.has_headers(has_headers)
.from_reader(file);
let headers: Option<Vec<String>> = match has_headers {
true => {
let hdrs = reader.headers().unwrap();
let longest = hdrs.iter().map(|h| h.len()).max().unwrap();
Some(
hdrs.into_iter()
.map(|h| format!("{:width$}", h, width = longest))
.collect(),
)
}
false => None,
};
for (i, record) in reader.records().enumerate() {
let record = record?;
let fields: Vec<&str> = record.iter().collect();
let num_flds = fields.len();
let hdrs = headers.clone().unwrap_or(
(1..=num_flds)
.into_iter()
.map(|n| format!("Field{:02}", n))
.collect::<Vec<String>>(),
);
println!(
"// ****** Record {} ****** //\n{}\n",
i + 1,
hdrs.iter()
.zip(fields.iter())
.map(|(hdr, val)| format!("{:>} : {}", hdr, val))
.collect::<Vec<String>>()
.join("\n")
);
}
}
Err(e) => eprintln!("{}: {}", filename, e),
}
Ok(())
}
// --------------------------------------------------
//fn format_record(
// record: StringRecord,
// headers: &Option<Vec<String>>,
//) -> String {
// let fields: Vec<&str> = record.iter().collect();
// let num_flds = fields.len();
// let hdrs = headers.as_ref().unwrap_or(
// (1..=num_flds)
// .into_iter()
// .map(|n| format!("Field{}", n))
// .collect().cloned(),
// );
// hdrs.iter()
// .zip(fields.iter())
// .map(|(hdr, val)| format!("{:>20}: {}", hdr, val))
// .collect::<Vec<&String>>()
// .join("\n")
//}
// --------------------------------------------------
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
|
#[macro_export]
macro_rules! emoji {
(":100:") => {
"💯"
};
(":1234:") => {
"🔢"
};
(":8ball:") => {
"🎱"
};
(":a:") => {
"🅰"
};
(":ab:") => {
"🆎"
};
(":abc:") => {
"🔤"
};
(":abcd:") => {
"🔡"
};
(":accept:") => {
'🉑'
};
(":adult:") => {
"🧑"
};
(":adult_tone1:") => {
"🧑🏻"
};
(":adult_tone2:") => {
"🧑🏼"
};
(":adult_tone3:") => {
"🧑🏽"
};
(":adult_tone4:") => {
"🧑🏾"
};
(":adult_tone5:") => {
"🧑🏿"
};
(":aerial_tramway:") => {
"🚡"
};
(":airplane:") => {
"✈"
};
(":airplane_arriving:") => {
"🛬"
};
(":airplane_departure:") => {
"🛫"
};
(":airplane_small:") => {
"🛩"
};
(":alarm_clock:") => {
"⏰"
};
(":alembic:") => {
"⚗"
};
(":alien:") => {
"👽"
};
(":ambulance:") => {
"🚑"
};
(":amphora:") => {
"🏺"
};
(":anchor:") => {
"⚓"
};
(":angel:") => {
"👼"
};
(":angel_tone1:") => {
"👼🏻"
};
(":angel_tone2:") => {
"👼🏼"
};
(":angel_tone3:") => {
"👼🏽"
};
(":angel_tone4:") => {
"👼🏾"
};
(":angel_tone5:") => {
"👼🏿"
};
(":anger:") => {
"💢"
};
(":anger_right:") => {
"🗯"
};
(":angry:") => {
"😠"
};
(":anguished:") => {
"😧"
};
(":ant:") => {
"🐜"
};
(":apple:") => {
"🍎"
};
(":aquarius:") => {
"♒"
};
(":aries:") => {
"♈"
};
(":arrow_backward:") => {
"◀"
};
(":arrow_double_down:") => {
"⏬"
};
(":arrow_double_up:") => {
"⏫"
};
(":arrow_down:") => {
"⬇"
};
(":arrow_down_small:") => {
"🔽"
};
(":arrow_forward:") => {
"▶"
};
(":arrow_heading_down:") => {
"⤵"
};
(":arrow_heading_up:") => {
"⤴"
};
(":arrow_left:") => {
"⬅"
};
(":arrow_lower_left:") => {
"↙"
};
(":arrow_lower_right:") => {
"↘"
};
(":arrow_right:") => {
"➡"
};
(":arrow_right_hook:") => {
"↪"
};
(":arrow_up:") => {
"⬆"
};
(":arrow_up_down:") => {
"↕"
};
(":arrow_up_small:") => {
"🔼"
};
(":arrow_upper_left:") => {
"↖"
};
(":arrow_upper_right:") => {
"↗"
};
(":arrows_clockwise:") => {
"🔃"
};
(":arrows_counterclockwise:") => {
"🔄"
};
(":art:") => {
"🎨"
};
(":articulated_lorry:") => {
"🚛"
};
(":asterisk:") => {
"*⃣"
};
(":asterisk_symbol:") => {
"*"
};
(":astonished:") => {
"😲"
};
(":athletic_shoe:") => {
"👟"
};
(":atm:") => {
"🏧"
};
(":atom:") => {
"⚛"
};
(":avocado:") => {
"🥑"
};
(":b:") => {
"🅱"
};
(":baby:") => {
"👶"
};
(":baby_bottle:") => {
"🍼"
};
(":baby_chick:") => {
"🐤"
};
(":baby_symbol:") => {
"🚼"
};
(":baby_tone1:") => {
"👶🏻"
};
(":baby_tone2:") => {
"👶🏼"
};
(":baby_tone3:") => {
"👶🏽"
};
(":baby_tone4:") => {
"👶🏾"
};
(":baby_tone5:") => {
"👶🏿"
};
(":back:") => {
"🔙"
};
(":bacon:") => {
"🥓"
};
(":badminton:") => {
"🏸"
};
(":baggage_claim:") => {
"🛄"
};
(":balloon:") => {
"🎈"
};
(":ballot_box:") => {
"🗳"
};
(":ballot_box_with_check:") => {
"☑"
};
(":bamboo:") => {
"🎍"
};
(":banana:") => {
"🍌"
};
(":bangbang:") => {
"‼"
};
(":bank:") => {
"🏦"
};
(":bar_chart:") => {
"📊"
};
(":barber:") => {
"💈"
};
(":baseball:") => {
"⚾"
};
(":basketball:") => {
"🏀"
};
(":bat:") => {
"🦇"
};
(":bath:") => {
"🛀"
};
(":bath_tone1:") => {
"🛀🏻"
};
(":bath_tone2:") => {
"🛀🏼"
};
(":bath_tone3:") => {
"🛀🏽"
};
(":bath_tone4:") => {
"🛀🏾"
};
(":bath_tone5:") => {
"🛀🏿"
};
(":bathtub:") => {
"🛁"
};
(":battery:") => {
"🔋"
};
(":beach:") => {
"🏖"
};
(":beach_umbrella:") => {
"⛱"
};
(":bear:") => {
"🐻"
};
(":bearded_person:") => {
"🧔"
};
(":bearded_person_tone1:") => {
"🧔🏻"
};
(":bearded_person_tone2:") => {
"🧔🏼"
};
(":bearded_person_tone3:") => {
"🧔🏽"
};
(":bearded_person_tone4:") => {
"🧔🏾"
};
(":bearded_person_tone5:") => {
"🧔🏿"
};
(":bed:") => {
"🛏"
};
(":bee:") => {
"🐝"
};
(":beer:") => {
"🍺"
};
(":beers:") => {
"🍻"
};
(":beetle:") => {
"🐞"
};
(":beginner:") => {
"🔰"
};
(":bell:") => {
"🔔"
};
(":bellhop:") => {
"🛎"
};
(":bento:") => {
"🍱"
};
(":bike:") => {
"🚲"
};
(":bikini:") => {
"👙"
};
(":billed_cap:") => {
"🧢"
};
(":biohazard:") => {
"☣"
};
(":bird:") => {
"🐦"
};
(":birthday:") => {
"🎂"
};
(":black_circle:") => {
"⚫"
};
(":black_heart:") => {
"🖤"
};
(":black_joker:") => {
"🃏"
};
(":black_large_square:") => {
"⬛"
};
(":black_medium_small_square:") => {
"◾"
};
(":black_medium_square:") => {
"◼"
};
(":black_nib:") => {
"✒"
};
(":black_small_square:") => {
"▪"
};
(":black_square_button:") => {
"🔲"
};
(":blond-haired_man:") => {
"👱♂"
};
(":blond-haired_man_tone1:") => {
"👱🏻♂"
};
(":blond-haired_man_tone2:") => {
"👱🏼���"
};
(":blond-haired_man_tone3:") => {
"👱🏽♂"
};
(":blond-haired_man_tone4:") => {
"👱🏾♂"
};
(":blond-haired_man_tone5:") => {
"👱🏿♂"
};
(":blond-haired_woman:") => {
"👱♀"
};
(":blond-haired_woman_tone1:") => {
"👱🏻♀"
};
(":blond-haired_woman_tone2:") => {
"👱🏼♀"
};
(":blond-haired_woman_tone3:") => {
"👱🏽♀"
};
(":blond-haired_woman_tone4:") => {
"👱🏾♀"
};
(":blond-haired_woman_tone5:") => {
"👱🏿♀"
};
(":blond_haired_person:") => {
"👱"
};
(":blond_haired_person_tone1:") => {
"👱🏻"
};
(":blond_haired_person_tone2:") => {
"👱🏼"
};
(":blond_haired_person_tone3:") => {
"👱🏽"
};
(":blond_haired_person_tone4:") => {
"👱🏾"
};
(":blond_haired_person_tone5:") => {
"👱🏿"
};
(":blossom:") => {
"🌼"
};
(":blowfish:") => {
"🐡"
};
(":blue_book:") => {
"📘"
};
(":blue_car:") => {
"🚙"
};
(":blue_circle:") => {
"🔵"
};
(":blue_heart:") => {
"💙"
};
(":blush:") => {
"😊"
};
(":boar:") => {
"🐗"
};
(":bomb:") => {
"💣"
};
(":book:") => {
"📖"
};
(":bookmark:") => {
"🔖"
};
(":bookmark_tabs:") => {
"📑"
};
(":books:") => {
"📚"
};
(":boom:") => {
"💥"
};
(":boot:") => {
"👢"
};
(":bouquet:") => {
"💐"
};
(":bow_and_arrow:") => {
"🏹"
};
(":bowl_with_spoon:") => {
"🥣"
};
(":bowling:") => {
"🎳"
};
(":boxing_glove:") => {
"🥊"
};
(":boy:") => {
"👦"
};
(":boy_tone1:") => {
"👦🏻"
};
(":boy_tone2:") => {
"👦🏼"
};
(":boy_tone3:") => {
"👦🏽"
};
(":boy_tone4:") => {
"👦🏾"
};
(":boy_tone5:") => {
"👦🏿"
};
(":brain:") => {
"🧠"
};
(":bread:") => {
"🍞"
};
(":breast_feeding:") => {
"🤱"
};
(":breast_feeding_tone1:") => {
"🤱🏻"
};
(":breast_feeding_tone2:") => {
"🤱🏼"
};
(":breast_feeding_tone3:") => {
"🤱🏽"
};
(":breast_feeding_tone4:") => {
"🤱🏾"
};
(":breast_feeding_tone5:") => {
"🤱🏿"
};
(":bride_with_veil:") => {
"👰"
};
(":bride_with_veil_tone1:") => {
"👰🏻"
};
(":bride_with_veil_tone2:") => {
"👰🏼"
};
(":bride_with_veil_tone3:") => {
"👰🏽"
};
(":bride_with_veil_tone4:") => {
"👰🏾"
};
(":bride_with_veil_tone5:") => {
"👰🏿"
};
(":bridge_at_night:") => {
"🌉"
};
(":briefcase:") => {
"💼"
};
(":broccoli:") => {
"🥦"
};
(":broken_heart:") => {
"💔"
};
(":bug:") => {
"🐛"
};
(":bulb:") => {
"💡"
};
(":bullettrain_front:") => {
"🚅"
};
(":bullettrain_side:") => {
"🚄"
};
(":burrito:") => {
"🌯"
};
(":bus:") => {
"🚌"
};
(":busstop:") => {
"🚏"
};
(":bust_in_silhouette:") => {
"👤"
};
(":busts_in_silhouette:") => {
"👥"
};
(":butterfly:") => {
"🦋"
};
(":cactus:") => {
"🌵"
};
(":cake:") => {
"🍰"
};
(":calendar:") => {
"📆"
};
(":calendar_spiral:") => {
"🗓"
};
(":call_me:") => {
"🤙"
};
(":call_me_tone1:") => {
"🤙🏻"
};
(":call_me_tone2:") => {
"🤙🏼"
};
(":call_me_tone3:") => {
"🤙🏽"
};
(":call_me_tone4:") => {
"🤙🏾"
};
(":call_me_tone5:") => {
"🤙🏿"
};
(":calling:") => {
"📲"
};
(":camel:") => {
"🐫"
};
(":camera:") => {
"📷"
};
(":camera_with_flash:") => {
"📸"
};
(":camping:") => {
"🏕"
};
(":cancer:") => {
"♋"
};
(":candle:") => {
"🕯"
};
(":candy:") => {
"🍬"
};
(":canned_food:") => {
"🥫"
};
(":canoe:") => {
"🛶"
};
(":capital_abcd:") => {
"🔠"
};
(":capricorn:") => {
"♑"
};
(":card_box:") => {
"🗃"
};
(":card_index:") => {
"📇"
};
(":carousel_horse:") => {
"🎠"
};
(":carrot:") => {
"🥕"
};
(":cat2:") => {
"🐈"
};
(":cat:") => {
"🐱"
};
(":cd:") => {
"💿"
};
(":chains:") => {
"⛓"
};
(":champagne:") => {
"🍾"
};
(":champagne_glass:") => {
"🥂"
};
(":chart:") => {
"💹"
};
(":chart_with_downwards_trend:") => {
"📉"
};
(":chart_with_upwards_trend:") => {
"📈"
};
(":checkered_flag:") => {
"🏁"
};
(":cheese:") => {
"🧀"
};
(":cherries:") => {
"🍒"
};
(":cherry_blossom:") => {
"🌸"
};
(":chestnut:") => {
"🌰"
};
(":chicken:") => {
"🐔"
};
(":child:") => {
"🧒"
};
(":child_tone1:") => {
"🧒🏻"
};
(":child_tone2:") => {
"🧒🏼"
};
(":child_tone3:") => {
"🧒🏽"
};
(":child_tone4:") => {
"🧒🏾"
};
(":child_tone5:") => {
"🧒🏿"
};
(":children_crossing:") => {
"🚸"
};
(":chipmunk:") => {
"🐿"
};
(":chocolate_bar:") => {
"🍫"
};
(":chopsticks:") => {
"🥢"
};
(":christmas_tree:") => {
"🎄"
};
(":church:") => {
"⛪"
};
(":cinema:") => {
"🎦"
};
(":circus_tent:") => {
"🎪"
};
(":city_dusk:") => {
"🌆"
};
(":city_sunset:") => {
"🌇"
};
(":cityscape:") => {
"🏙"
};
(":cl:") => {
"🆑"
};
(":clap:") => {
"👏"
};
(":clap_tone1:") => {
"👏🏻"
};
(":clap_tone2:") => {
"👏🏼"
};
(":clap_tone3:") => {
"👏🏽"
};
(":clap_tone4:") => {
"👏🏾"
};
(":clap_tone5:") => {
"👏🏿"
};
(":clapper:") => {
"🎬"
};
(":classical_building:") => {
"🏛"
};
(":clipboard:") => {
"📋"
};
(":clock1030:") => {
"🕥"
};
(":clock10:") => {
"🕙"
};
(":clock1130:") => {
"🕦"
};
(":clock11:") => {
"🕚"
};
(":clock1230:") => {
"🕧"
};
(":clock12:") => {
"🕛"
};
(":clock130:") => {
"🕜"
};
(":clock1:") => {
"🕐"
};
(":clock230:") => {
"🕝"
};
(":clock2:") => {
"🕑"
};
(":clock330:") => {
"🕞"
};
(":clock3:") => {
"🕒"
};
(":clock430:") => {
"🕟"
};
(":clock4:") => {
"🕓"
};
(":clock530:") => {
"🕠"
};
(":clock5:") => {
"🕔"
};
(":clock630:") => {
"🕡"
};
(":clock6:") => {
"🕕"
};
(":clock730:") => {
"🕢"
};
(":clock7:") => {
"🕖"
};
(":clock830:") => {
"🕣"
};
(":clock8:") => {
"🕗"
};
(":clock930:") => {
"🕤"
};
(":clock9:") => {
"🕘"
};
(":clock:") => {
"🕰"
};
(":closed_book:") => {
"📕"
};
(":closed_lock_with_key:") => {
"🔐"
};
(":closed_umbrella:") => {
"🌂"
};
(":cloud:") => {
"☁"
};
(":cloud_lightning:") => {
"🌩"
};
(":cloud_rain:") => {
"🌧"
};
(":cloud_snow:") => {
"🌨"
};
(":cloud_tornado:") => {
"🌪"
};
(":clown:") => {
"🤡"
};
(":clubs:") => {
"♣"
};
(":coat:") => {
"🧥"
};
(":cocktail:") => {
"🍸"
};
(":coconut:") => {
"🥥"
};
(":coffee:") => {
"☕"
};
(":coffin:") => {
"⚰"
};
(":cold_sweat:") => {
"😰"
};
(":comet:") => {
"☄"
};
(":compression:") => {
"🗜"
};
(":computer:") => {
"💻"
};
(":confetti_ball:") => {
"🎊"
};
(":confounded:") => {
"😖"
};
(":confused:") => {
"😕"
};
(":congratulations:") => {
"㊗"
};
(":construction:") => {
"🚧"
};
(":construction_site:") => {
"🏗"
};
(":construction_worker:") => {
"👷"
};
(":construction_worker_tone1:") => {
"👷🏻"
};
(":construction_worker_tone2:") => {
"👷🏼"
};
(":construction_worker_tone3:") => {
"👷🏽"
};
(":construction_worker_tone4:") => {
"👷🏾"
};
(":construction_worker_tone5:") => {
"👷🏿"
};
(":control_knobs:") => {
"🎛"
};
(":convenience_store:") => {
"🏪"
};
(":cookie:") => {
"🍪"
};
(":cooking:") => {
"🍳"
};
(":cool:") => {
"🆒"
};
(":copyright:") => {
"©"
};
(":corn:") => {
"🌽"
};
(":couch:") => {
"🛋"
};
(":couple:") => {
"👫"
};
(":couple_mm:") => {
"👨❤👨"
};
(":couple_with_heart:") => {
"💑"
};
(":couple_with_heart_woman_man:") => {
"👩❤👨"
};
(":couple_ww:") => {
"👩❤👩"
};
(":couplekiss:") => {
"💏"
};
(":cow2:") => {
"🐄"
};
(":cow:") => {
"🐮"
};
(":cowboy:") => {
"🤠"
};
(":crab:") => {
"🦀"
};
(":crayon:") => {
"🖍"
};
(":crazy_face:") => {
"🤪"
};
(":credit_card:") => {
"💳"
};
(":crescent_moon:") => {
"🌙"
};
(":cricket:") => {
"🦗"
};
(":cricket_game:") => {
"🏏"
};
(":crocodile:") => {
"🐊"
};
(":croissant:") => {
"🥐"
};
(":cross:") => {
"✝"
};
(":crossed_flags:") => {
"🎌"
};
(":crossed_swords:") => {
"⚔"
};
(":crown:") => {
"👑"
};
(":cruise_ship:") => {
"🛳"
};
(":cry:") => {
"😢"
};
(":crying_cat_face:") => {
"😿"
};
(":crystal_ball:") => {
"🔮"
};
(":cucumber:") => {
"🥒"
};
(":cup_with_straw:") => {
"🥤"
};
(":cupid:") => {
"💘"
};
(":curling_stone:") => {
"🥌"
};
(":curly_loop:") => {
"➰"
};
(":currency_exchange:") => {
"💱"
};
(":curry:") => {
"🍛"
};
(":custard:") => {
"🍮"
};
(":customs:") => {
"🛃"
};
(":cut_of_meat:") => {
"🥩"
};
(":cyclone:") => {
"🌀"
};
(":dagger:") => {
"🗡"
};
(":dancer:") => {
"💃"
};
(":dancer_tone1:") => {
"💃🏻"
};
(":dancer_tone2:") => {
"💃🏼"
};
(":dancer_tone3:") => {
"💃🏽"
};
(":dancer_tone4:") => {
"💃🏾"
};
(":dancer_tone5:") => {
"💃🏿"
};
(":dango:") => {
"🍡"
};
(":dark_sunglasses:") => {
"🕶"
};
(":dart:") => {
"🎯"
};
(":dash:") => {
"💨"
};
(":date:") => {
"📅"
};
(":deciduous_tree:") => {
"🌳"
};
(":deer:") => {
"🦌"
};
(":department_store:") => {
"🏬"
};
(":desert:") => {
"🏜"
};
(":desktop:") => {
"🖥"
};
(":detective:") => {
"🕵"
};
(":detective_tone1:") => {
"🕵🏻"
};
(":detective_tone2:") => {
"🕵🏼"
};
(":detective_tone3:") => {
"🕵🏽"
};
(":detective_tone4:") => {
"🕵🏾"
};
(":detective_tone5:") => {
"🕵🏿"
};
(":diamond_shape_with_a_dot_inside:") => {
"💠"
};
(":diamonds:") => {
"♦"
};
(":digit_eight:") => {
"8"
};
(":digit_five:") => {
"5"
};
(":digit_four:") => {
"4"
};
(":digit_nine:") => {
"9"
};
(":digit_one:") => {
"1"
};
(":digit_seven:") => {
"7"
};
(":digit_six:") => {
"6"
};
(":digit_three:") => {
"3"
};
(":digit_two:") => {
"2"
};
(":digit_zero:") => {
"0"
};
(":disappointed:") => {
"😞"
};
(":disappointed_relieved:") => {
"😥"
};
(":dividers:") => {
"🗂"
};
(":dizzy:") => {
"💫"
};
(":dizzy_face:") => {
"😵"
};
(":do_not_litter:") => {
"🚯"
};
(":dog2:") => {
"🐕"
};
(":dog:") => {
"🐶"
};
(":dollar:") => {
"💵"
};
(":dolls:") => {
"🎎"
};
(":dolphin:") => {
"🐬"
};
(":door:") => {
"🚪"
};
(":doughnut:") => {
"🍩"
};
(":dove:") => {
"🕊"
};
(":dragon:") => {
"🐉"
};
(":dragon_face:") => {
"🐲"
};
(":dress:") => {
"👗"
};
(":dromedary_camel:") => {
"🐪"
};
(":drooling_face:") => {
"🤤"
};
(":droplet:") => {
"💧"
};
(":drum:") => {
"🥁"
};
(":duck:") => {
"🦆"
};
(":dumpling:") => {
"🥟"
};
(":dvd:") => {
"📀"
};
(":e-mail:") => {
"📧"
};
(":eagle:") => {
"🦅"
};
(":ear:") => {
"👂"
};
(":ear_of_rice:") => {
"🌾"
};
(":ear_tone1:") => {
"👂🏻"
};
(":ear_tone2:") => {
"👂🏼"
};
(":ear_tone3:") => {
"👂🏽"
};
(":ear_tone4:") => {
"👂🏾"
};
(":ear_tone5:") => {
"👂🏿"
};
(":earth_africa:") => {
"🌍"
};
(":earth_americas:") => {
"🌎"
};
(":earth_asia:") => {
"🌏"
};
(":egg:") => {
"🥚"
};
(":eggplant:") => {
"🍆"
};
(":eight:") => {
"8⃣"
};
(":eight_pointed_black_star:") => {
"✴"
};
(":eight_spoked_asterisk:") => {
"✳"
};
(":eject:") => {
"⏏"
};
(":electric_plug:") => {
"🔌"
};
(":elephant:") => {
"🐘"
};
(":elf:") => {
"🧝"
};
(":elf_tone1:") => {
"🧝🏻"
};
(":elf_tone2:") => {
"🧝🏼"
};
(":elf_tone3:") => {
"🧝🏽"
};
(":elf_tone4:") => {
"🧝🏾"
};
(":elf_tone5:") => {
"🧝🏿"
};
(":end:") => {
"🔚"
};
(":england:") => {
"🏴"
};
(":envelope:") => {
"✉"
};
(":envelope_with_arrow:") => {
"📩"
};
(":euro:") => {
"💶"
};
(":european_castle:") => {
"🏰"
};
(":european_post_office:") => {
"🏤"
};
(":evergreen_tree:") => {
"🌲"
};
(":exclamation:") => {
"❗"
};
(":exploding_head:") => {
"🤯"
};
(":expressionless:") => {
"😑"
};
(":eye:") => {
"👁"
};
(":eye_in_speech_bubble:") => {
"👁🗨"
};
(":eyeglasses:") => {
"👓"
};
(":eyes:") => {
"👀"
};
(":face_vomiting:") => {
"🤮"
};
(":face_with_hand_over_mouth:") => {
"🤭"
};
(":face_with_monocle:") => {
"🧐"
};
(":face_with_raised_eyebrow:") => {
"🤨"
};
(":face_with_symbols_over_mouth:") => {
"🤬"
};
(":factory:") => {
"🏭"
};
(":fairy:") => {
"🧚"
};
(":fairy_tone1:") => {
"🧚🏻"
};
(":fairy_tone2:") => {
"🧚🏼"
};
(":fairy_tone3:") => {
"🧚🏽"
};
(":fairy_tone4:") => {
"🧚🏾"
};
(":fairy_tone5:") => {
"🧚🏿"
};
(":fallen_leaf:") => {
"🍂"
};
(":family:") => {
"👪"
};
(":family_man_boy:") => {
"👨👦"
};
(":family_man_boy_boy:") => {
"👨👦👦"
};
(":family_man_girl:") => {
"👨👧"
};
(":family_man_girl_boy:") => {
"👨👧👦"
};
(":family_man_girl_girl:") => {
"👨👧👧"
};
(":family_man_woman_boy:") => {
"👨👩👦"
};
(":family_mmb:") => {
"👨👨👦"
};
(":family_mmbb:") => {
"👨👨👦👦"
};
(":family_mmg:") => {
"👨👨👧"
};
(":family_mmgb:") => {
"👨👨👧👦"
};
(":family_mmgg:") => {
"👨👨👧👧"
};
(":family_mwbb:") => {
"👨👩👦👦"
};
(":family_mwg:") => {
"👨👩👧"
};
(":family_mwgb:") => {
"👨👩👧👦"
};
(":family_mwgg:") => {
"👨👩👧👧"
};
(":family_woman_boy:") => {
"👩👦"
};
(":family_woman_boy_boy:") => {
"👩👦👦"
};
(":family_woman_girl:") => {
"👩👧"
};
(":family_woman_girl_boy:") => {
"👩👧👦"
};
(":family_woman_girl_girl:") => {
"👩👧👧"
};
(":family_wwb:") => {
"👩👩👦"
};
(":family_wwbb:") => {
"👩👩👦👦"
};
(":family_wwg:") => {
"👩👩👧"
};
(":family_wwgb:") => {
"👩👩👧👦"
};
(":family_wwgg:") => {
"👩👩👧👧"
};
(":fast_forward:") => {
"⏩"
};
(":fax:") => {
"📠"
};
(":fearful:") => {
"😨"
};
(":feet:") => {
"🐾"
};
(":female_sign:") => {
"♀"
};
(":ferris_wheel:") => {
"🎡"
};
(":ferry:") => {
"⛴"
};
(":field_hockey:") => {
"🏑"
};
(":file_cabinet:") => {
"🗄"
};
(":file_folder:") => {
"📁"
};
(":film_frames:") => {
"🎞"
};
(":fingers_crossed:") => {
"🤞"
};
(":fingers_crossed_tone1:") => {
"🤞🏻"
};
(":fingers_crossed_tone2:") => {
"🤞🏼"
};
(":fingers_crossed_tone3:") => {
"🤞🏽"
};
(":fingers_crossed_tone4:") => {
"🤞🏾"
};
(":fingers_crossed_tone5:") => {
"🤞🏿"
};
(":fire:") => {
"🔥"
};
(":fire_engine:") => {
"🚒"
};
(":fireworks:") => {
"🎆"
};
(":first_place:") => {
"🥇"
};
(":first_quarter_moon:") => {
"🌓"
};
(":first_quarter_moon_with_face:") => {
"🌛"
};
(":fish:") => {
"🐟"
};
(":fish_cake:") => {
"🍥"
};
(":fishing_pole_and_fish:") => {
"🎣"
};
(":fist:") => {
"✊"
};
(":fist_tone1:") => {
"✊🏻"
};
(":fist_tone2:") => {
"✊🏼"
};
(":fist_tone3:") => {
"✊🏽"
};
(":fist_tone4:") => {
"✊🏾"
};
(":fist_tone5:") => {
"✊🏿"
};
(":five:") => {
"5⃣"
};
(":flag_ac:") => {
"🇦🇨"
};
(":flag_ad:") => {
"🇦🇩"
};
(":flag_ae:") => {
"🇦🇪"
};
(":flag_af:") => {
"🇦🇫"
};
(":flag_ag:") => {
"🇦🇬"
};
(":flag_ai:") => {
"🇦🇮"
};
(":flag_al:") => {
"🇦🇱"
};
(":flag_am:") => {
"🇦🇲"
};
(":flag_ao:") => {
"🇦🇴"
};
(":flag_aq:") => {
"🇦🇶"
};
(":flag_ar:") => {
"🇦🇷"
};
(":flag_as:") => {
"🇦🇸"
};
(":flag_at:") => {
"🇦🇹"
};
(":flag_au:") => {
"🇦🇺"
};
(":flag_aw:") => {
"🇦🇼"
};
(":flag_ax:") => {
"🇦🇽"
};
(":flag_az:") => {
"🇦🇿"
};
(":flag_ba:") => {
"🇧🇦"
};
(":flag_bb:") => {
"🇧🇧"
};
(":flag_bd:") => {
"🇧🇩"
};
(":flag_be:") => {
"🇧🇪"
};
(":flag_bf:") => {
"🇧🇫"
};
(":flag_bg:") => {
"🇧🇬"
};
(":flag_bh:") => {
"🇧🇭"
};
(":flag_bi:") => {
"🇧🇮"
};
(":flag_bj:") => {
"🇧🇯"
};
(":flag_bl:") => {
"🇧🇱"
};
(":flag_black:") => {
"🏴"
};
(":flag_bm:") => {
"🇧🇲"
};
(":flag_bn:") => {
"🇧🇳"
};
(":flag_bo:") => {
"🇧🇴"
};
(":flag_bq:") => {
"🇧🇶"
};
(":flag_br:") => {
"🇧🇷"
};
(":flag_bs:") => {
"🇧🇸"
};
(":flag_bt:") => {
"🇧🇹"
};
(":flag_bv:") => {
"🇧🇻"
};
(":flag_bw:") => {
"🇧🇼"
};
(":flag_by:") => {
"🇧🇾"
};
(":flag_bz:") => {
"🇧🇿"
};
(":flag_ca:") => {
"🇨🇦"
};
(":flag_cc:") => {
"🇨🇨"
};
(":flag_cd:") => {
"🇨🇩"
};
(":flag_cf:") => {
"🇨🇫"
};
(":flag_cg:") => {
"🇨🇬"
};
(":flag_ch:") => {
"🇨🇭"
};
(":flag_ci:") => {
"🇨🇮"
};
(":flag_ck:") => {
"🇨🇰"
};
(":flag_cl:") => {
"🇨🇱"
};
(":flag_cm:") => {
"🇨🇲"
};
(":flag_cn:") => {
"🇨🇳"
};
(":flag_co:") => {
"🇨🇴"
};
(":flag_cp:") => {
"🇨🇵"
};
(":flag_cr:") => {
"🇨🇷"
};
(":flag_cu:") => {
"🇨🇺"
};
(":flag_cv:") => {
"🇨🇻"
};
(":flag_cw:") => {
"🇨🇼"
};
(":flag_cx:") => {
"🇨🇽"
};
(":flag_cy:") => {
"🇨🇾"
};
(":flag_cz:") => {
"🇨🇿"
};
(":flag_de:") => {
"🇩🇪"
};
(":flag_dg:") => {
"🇩🇬"
};
(":flag_dj:") => {
"🇩🇯"
};
(":flag_dk:") => {
"🇩🇰"
};
(":flag_dm:") => {
"🇩🇲"
};
(":flag_do:") => {
"🇩🇴"
};
(":flag_dz:") => {
"🇩🇿"
};
(":flag_ea:") => {
"🇪🇦"
};
(":flag_ec:") => {
"🇪🇨"
};
(":flag_ee:") => {
"🇪🇪"
};
(":flag_eg:") => {
"🇪🇬"
};
(":flag_eh:") => {
"🇪🇭"
};
(":flag_er:") => {
"🇪🇷"
};
(":flag_es:") => {
"🇪🇸"
};
(":flag_et:") => {
"🇪🇹"
};
(":flag_eu:") => {
"🇪🇺"
};
(":flag_fi:") => {
"🇫🇮"
};
(":flag_fj:") => {
"🇫🇯"
};
(":flag_fk:") => {
"🇫🇰"
};
(":flag_fm:") => {
"🇫🇲"
};
(":flag_fo:") => {
"🇫🇴"
};
(":flag_fr:") => {
"🇫🇷"
};
(":flag_ga:") => {
"🇬🇦"
};
(":flag_gb:") => {
"🇬🇧"
};
(":flag_gd:") => {
"🇬🇩"
};
(":flag_ge:") => {
"🇬🇪"
};
(":flag_gf:") => {
"🇬🇫"
};
(":flag_gg:") => {
"🇬🇬"
};
(":flag_gh:") => {
"🇬🇭"
};
(":flag_gi:") => {
"🇬🇮"
};
(":flag_gl:") => {
"🇬🇱"
};
(":flag_gm:") => {
"🇬🇲"
};
(":flag_gn:") => {
"🇬🇳"
};
(":flag_gp:") => {
"🇬🇵"
};
(":flag_gq:") => {
"🇬🇶"
};
(":flag_gr:") => {
"🇬🇷"
};
(":flag_gs:") => {
"🇬🇸"
};
(":flag_gt:") => {
"🇬🇹"
};
(":flag_gu:") => {
"🇬🇺"
};
(":flag_gw:") => {
"🇬🇼"
};
(":flag_gy:") => {
"🇬🇾"
};
(":flag_hk:") => {
"🇭🇰"
};
(":flag_hm:") => {
"🇭🇲"
};
(":flag_hn:") => {
"🇭🇳"
};
(":flag_hr:") => {
"🇭🇷"
};
(":flag_ht:") => {
"🇭🇹"
};
(":flag_hu:") => {
"🇭🇺"
};
(":flag_ic:") => {
"🇮🇨"
};
(":flag_id:") => {
"🇮🇩"
};
(":flag_ie:") => {
"🇮🇪"
};
(":flag_il:") => {
"🇮🇱"
};
(":flag_im:") => {
"🇮🇲"
};
(":flag_in:") => {
"🇮🇳"
};
(":flag_io:") => {
"🇮🇴"
};
(":flag_iq:") => {
"🇮🇶"
};
(":flag_ir:") => {
"🇮🇷"
};
(":flag_is:") => {
"🇮🇸"
};
(":flag_it:") => {
"🇮🇹"
};
(":flag_je:") => {
"🇯🇪"
};
(":flag_jm:") => {
"🇯🇲"
};
(":flag_jo:") => {
"🇯🇴"
};
(":flag_jp:") => {
"🇯🇵"
};
(":flag_ke:") => {
"🇰🇪"
};
(":flag_kg:") => {
"🇰🇬"
};
(":flag_kh:") => {
"🇰🇭"
};
(":flag_ki:") => {
"🇰🇮"
};
(":flag_km:") => {
"🇰🇲"
};
(":flag_kn:") => {
"🇰🇳"
};
(":flag_kp:") => {
"🇰🇵"
};
(":flag_kr:") => {
"🇰🇷"
};
(":flag_kw:") => {
"🇰🇼"
};
(":flag_ky:") => {
"🇰🇾"
};
(":flag_kz:") => {
"🇰🇿"
};
(":flag_la:") => {
"🇱🇦"
};
(":flag_lb:") => {
"🇱🇧"
};
(":flag_lc:") => {
"🇱🇨"
};
(":flag_li:") => {
"🇱🇮"
};
(":flag_lk:") => {
"🇱🇰"
};
(":flag_lr:") => {
"🇱🇷"
};
(":flag_ls:") => {
"🇱🇸"
};
(":flag_lt:") => {
"����🇹"
};
(":flag_lu:") => {
"🇱🇺"
};
(":flag_lv:") => {
"🇱🇻"
};
(":flag_ly:") => {
"🇱🇾"
};
(":flag_ma:") => {
"🇲🇦"
};
(":flag_mc:") => {
"🇲🇨"
};
(":flag_md:") => {
"🇲🇩"
};
(":flag_me:") => {
"🇲🇪"
};
(":flag_mf:") => {
"🇲🇫"
};
(":flag_mg:") => {
"🇲🇬"
};
(":flag_mh:") => {
"🇲🇭"
};
(":flag_mk:") => {
"🇲🇰"
};
(":flag_ml:") => {
"🇲🇱"
};
(":flag_mm:") => {
"🇲🇲"
};
(":flag_mn:") => {
"🇲🇳"
};
(":flag_mo:") => {
"🇲🇴"
};
(":flag_mp:") => {
"🇲🇵"
};
(":flag_mq:") => {
"🇲🇶"
};
(":flag_mr:") => {
"🇲🇷"
};
(":flag_ms:") => {
"🇲🇸"
};
(":flag_mt:") => {
"🇲🇹"
};
(":flag_mu:") => {
"🇲🇺"
};
(":flag_mv:") => {
"🇲🇻"
};
(":flag_mw:") => {
"🇲🇼"
};
(":flag_mx:") => {
"🇲🇽"
};
(":flag_my:") => {
"🇲🇾"
};
(":flag_mz:") => {
"🇲🇿"
};
(":flag_na:") => {
"🇳🇦"
};
(":flag_nc:") => {
"🇳🇨"
};
(":flag_ne:") => {
"🇳🇪"
};
(":flag_nf:") => {
"🇳🇫"
};
(":flag_ng:") => {
"🇳🇬"
};
(":flag_ni:") => {
"🇳🇮"
};
(":flag_nl:") => {
"🇳🇱"
};
(":flag_no:") => {
"🇳🇴"
};
(":flag_np:") => {
"🇳🇵"
};
(":flag_nr:") => {
"🇳🇷"
};
(":flag_nu:") => {
"🇳🇺"
};
(":flag_nz:") => {
"🇳🇿"
};
(":flag_om:") => {
"🇴🇲"
};
(":flag_pa:") => {
"🇵🇦"
};
(":flag_pe:") => {
"🇵🇪"
};
(":flag_pf:") => {
"🇵🇫"
};
(":flag_pg:") => {
"🇵🇬"
};
(":flag_ph:") => {
"🇵🇭"
};
(":flag_pk:") => {
"🇵🇰"
};
(":flag_pl:") => {
"🇵🇱"
};
(":flag_pm:") => {
"🇵🇲"
};
(":flag_pn:") => {
"🇵🇳"
};
(":flag_pr:") => {
"🇵🇷"
};
(":flag_ps:") => {
"🇵🇸"
};
(":flag_pt:") => {
"🇵🇹"
};
(":flag_pw:") => {
"🇵🇼"
};
(":flag_py:") => {
"🇵🇾"
};
(":flag_qa:") => {
"🇶🇦"
};
(":flag_re:") => {
"🇷🇪"
};
(":flag_ro:") => {
"🇷🇴"
};
(":flag_rs:") => {
"🇷🇸"
};
(":flag_ru:") => {
"🇷🇺"
};
(":flag_rw:") => {
"🇷🇼"
};
(":flag_sa:") => {
"🇸🇦"
};
(":flag_sb:") => {
"🇸🇧"
};
(":flag_sc:") => {
"🇸🇨"
};
(":flag_sd:") => {
"🇸🇩"
};
(":flag_se:") => {
"🇸🇪"
};
(":flag_sg:") => {
"🇸🇬"
};
(":flag_sh:") => {
"🇸🇭"
};
(":flag_si:") => {
"🇸🇮"
};
(":flag_sj:") => {
"🇸🇯"
};
(":flag_sk:") => {
"🇸🇰"
};
(":flag_sl:") => {
"🇸🇱"
};
(":flag_sm:") => {
"🇸🇲"
};
(":flag_sn:") => {
"🇸🇳"
};
(":flag_so:") => {
"🇸🇴"
};
(":flag_sr:") => {
"🇸🇷"
};
(":flag_ss:") => {
"🇸🇸"
};
(":flag_st:") => {
"🇸🇹"
};
(":flag_sv:") => {
"🇸🇻"
};
(":flag_sx:") => {
"🇸🇽"
};
(":flag_sy:") => {
"🇸🇾"
};
(":flag_sz:") => {
"🇸🇿"
};
(":flag_ta:") => {
"🇹🇦"
};
(":flag_tc:") => {
"🇹🇨"
};
(":flag_td:") => {
"🇹🇩"
};
(":flag_tf:") => {
"🇹🇫"
};
(":flag_tg:") => {
"🇹🇬"
};
(":flag_th:") => {
"🇹🇭"
};
(":flag_tj:") => {
"🇹🇯"
};
(":flag_tk:") => {
"🇹🇰"
};
(":flag_tl:") => {
"🇹🇱"
};
(":flag_tm:") => {
"🇹🇲"
};
(":flag_tn:") => {
"🇹🇳"
};
(":flag_to:") => {
"🇹🇴"
};
(":flag_tr:") => {
"🇹🇷"
};
(":flag_tt:") => {
"🇹🇹"
};
(":flag_tv:") => {
"🇹🇻"
};
(":flag_tw:") => {
"🇹🇼"
};
(":flag_tz:") => {
"🇹🇿"
};
(":flag_ua:") => {
"🇺🇦"
};
(":flag_ug:") => {
"🇺🇬"
};
(":flag_um:") => {
"🇺🇲"
};
(":flag_us:") => {
"🇺🇸"
};
(":flag_uy:") => {
"🇺🇾"
};
(":flag_uz:") => {
"🇺🇿"
};
(":flag_va:") => {
"🇻🇦"
};
(":flag_vc:") => {
"🇻🇨"
};
(":flag_ve:") => {
"🇻🇪"
};
(":flag_vg:") => {
"🇻🇬"
};
(":flag_vi:") => {
"🇻🇮"
};
(":flag_vn:") => {
"🇻🇳"
};
(":flag_vu:") => {
"🇻🇺"
};
(":flag_wf:") => {
"🇼🇫"
};
(":flag_white:") => {
"🏳"
};
(":flag_ws:") => {
"🇼🇸"
};
(":flag_xk:") => {
"🇽🇰"
};
(":flag_ye:") => {
"🇾🇪"
};
(":flag_yt:") => {
"🇾🇹"
};
(":flag_za:") => {
"🇿🇦"
};
(":flag_zm:") => {
"🇿🇲"
};
(":flag_zw:") => {
"🇿🇼"
};
(":flags:") => {
"🎏"
};
(":flashlight:") => {
"🔦"
};
(":fleur-de-lis:") => {
"⚜"
};
(":floppy_disk:") => {
"💾"
};
(":flower_playing_cards:") => {
"🎴"
};
(":flushed:") => {
"😳"
};
(":flying_saucer:") => {
"🛸"
};
(":fog:") => {
"🌫"
};
(":foggy:") => {
"🌁"
};
(":football:") => {
"🏈"
};
(":footprints:") => {
"👣"
};
(":fork_and_knife:") => {
"🍴"
};
(":fork_knife_plate:") => {
"🍽"
};
(":fortune_cookie:") => {
"🥠"
};
(":fountain:") => {
"⛲"
};
(":four:") => {
"4⃣"
};
(":four_leaf_clover:") => {
"🍀"
};
(":fox:") => {
"🦊"
};
(":frame_photo:") => {
"🖼"
};
(":free:") => {
"🆓"
};
(":french_bread:") => {
"🥖"
};
(":fried_shrimp:") => {
"🍤"
};
(":fries:") => {
"🍟"
};
(":frog:") => {
"🐸"
};
(":frowning2:") => {
"☹"
};
(":frowning:") => {
"😦"
};
(":fuelpump:") => {
"⛽"
};
(":full_moon:") => {
"🌕"
};
(":full_moon_with_face:") => {
"🌝"
};
(":game_die:") => {
"🎲"
};
(":gear:") => {
"⚙"
};
(":gem:") => {
"💎"
};
(":gemini:") => {
"♊"
};
(":genie:") => {
"🧞"
};
(":ghost:") => {
"👻"
};
(":gift:") => {
"🎁"
};
(":gift_heart:") => {
"💝"
};
(":giraffe:") => {
"🦒"
};
(":girl:") => {
"👧"
};
(":girl_tone1:") => {
"👧🏻"
};
(":girl_tone2:") => {
"👧🏼"
};
(":girl_tone3:") => {
"👧🏽"
};
(":girl_tone4:") => {
"👧🏾"
};
(":girl_tone5:") => {
"👧🏿"
};
(":globe_with_meridians:") => {
"🌐"
};
(":gloves:") => {
"🧤"
};
(":goal:") => {
"🥅"
};
(":goat:") => {
"🐐"
};
(":golf:") => {
"⛳"
};
(":gorilla:") => {
"🦍"
};
(":grapes:") => {
"🍇"
};
(":green_apple:") => {
"🍏"
};
(":green_book:") => {
"📗"
};
(":green_heart:") => {
"💚"
};
(":grey_exclamation:") => {
"❕"
};
(":grey_question:") => {
"❔"
};
(":grimacing:") => {
"😬"
};
(":grin:") => {
"😁"
};
(":grinning:") => {
"😀"
};
(":guard:") => {
"💂"
};
(":guard_tone1:") => {
"💂🏻"
};
(":guard_tone2:") => {
"💂🏼"
};
(":guard_tone3:") => {
"💂����"
};
(":guard_tone4:") => {
"💂🏾"
};
(":guard_tone5:") => {
"💂🏿"
};
(":guitar:") => {
"🎸"
};
(":gun:") => {
"🔫"
};
(":hamburger:") => {
"🍔"
};
(":hammer:") => {
"🔨"
};
(":hammer_pick:") => {
"⚒"
};
(":hamster:") => {
"🐹"
};
(":hand_splayed:") => {
"🖐"
};
(":hand_splayed_tone1:") => {
"🖐🏻"
};
(":hand_splayed_tone2:") => {
"🖐🏼"
};
(":hand_splayed_tone3:") => {
"🖐🏽"
};
(":hand_splayed_tone4:") => {
"🖐🏾"
};
(":hand_splayed_tone5:") => {
"🖐🏿"
};
(":handbag:") => {
"👜"
};
(":handshake:") => {
"🤝"
};
(":hash:") => {
"#⃣"
};
(":hatched_chick:") => {
"🐥"
};
(":hatching_chick:") => {
"🐣"
};
(":head_bandage:") => {
"🤕"
};
(":headphones:") => {
"🎧"
};
(":hear_no_evil:") => {
"🙉"
};
(":heart:") => {
"❤"
};
(":heart_decoration:") => {
"💟"
};
(":heart_exclamation:") => {
"❣"
};
(":heart_eyes:") => {
"😍"
};
(":heart_eyes_cat:") => {
"😻"
};
(":heartbeat:") => {
"💓"
};
(":heartpulse:") => {
"💗"
};
(":hearts:") => {
"♥"
};
(":heavy_check_mark:") => {
"✔"
};
(":heavy_division_sign:") => {
"➗"
};
(":heavy_dollar_sign:") => {
"💲"
};
(":heavy_minus_sign:") => {
"➖"
};
(":heavy_multiplication_x:") => {
"✖"
};
(":heavy_plus_sign:") => {
"➕"
};
(":hedgehog:") => {
"🦔"
};
(":helicopter:") => {
"🚁"
};
(":helmet_with_cross:") => {
"⛑"
};
(":herb:") => {
"🌿"
};
(":hibiscus:") => {
"🌺"
};
(":high_brightness:") => {
"🔆"
};
(":high_heel:") => {
"👠"
};
(":hockey:") => {
"🏒"
};
(":hole:") => {
"🕳"
};
(":homes:") => {
"🏘"
};
(":honey_pot:") => {
"🍯"
};
(":horse:") => {
"🐴"
};
(":horse_racing:") => {
"🏇"
};
(":horse_racing_tone1:") => {
"🏇🏻"
};
(":horse_racing_tone2:") => {
"🏇🏼"
};
(":horse_racing_tone3:") => {
"🏇🏽"
};
(":horse_racing_tone4:") => {
"🏇🏾"
};
(":horse_racing_tone5:") => {
"🏇🏿"
};
(":hospital:") => {
"🏥"
};
(":hot_pepper:") => {
"🌶"
};
(":hotdog:") => {
"🌭"
};
(":hotel:") => {
"🏨"
};
(":hotsprings:") => {
"♨"
};
(":hourglass:") => {
"⌛"
};
(":hourglass_flowing_sand:") => {
"⏳"
};
(":house:") => {
"🏠"
};
(":house_abandoned:") => {
"🏚"
};
(":house_with_garden:") => {
"🏡"
};
(":hugging:") => {
"🤗"
};
(":hushed:") => {
"😯"
};
(":ice_cream:") => {
"🍨"
};
(":ice_skate:") => {
"⛸"
};
(":icecream:") => {
"🍦"
};
(":id:") => {
"🆔"
};
(":ideograph_advantage:") => {
"🉐"
};
(":imp:") => {
"👿"
};
(":inbox_tray:") => {
"📥"
};
(":incoming_envelope:") => {
"📨"
};
(":information_source:") => {
"ℹ"
};
(":innocent:") => {
"😇"
};
(":interrobang:") => {
"⁉"
};
(":iphone:") => {
"📱"
};
(":island:") => {
"🏝"
};
(":izakaya_lantern:") => {
"🏮"
};
(":jack_o_lantern:") => {
"🎃"
};
(":japan:") => {
"🗾"
};
(":japanese_castle:") => {
"🏯"
};
(":japanese_goblin:") => {
"👺"
};
(":japanese_ogre:") => {
"👹"
};
(":jeans:") => {
"👖"
};
(":joy:") => {
"😂"
};
(":joy_cat:") => {
"😹"
};
(":joystick:") => {
"🕹"
};
(":kaaba:") => {
"🕋"
};
(":key2:") => {
"🗝"
};
(":key:") => {
"🔑"
};
(":keyboard:") => {
"⌨"
};
(":keycap_ten:") => {
"🔟"
};
(":kimono:") => {
"👘"
};
(":kiss:") => {
"💋"
};
(":kiss_mm:") => {
"👨❤💋👨"
};
(":kiss_woman_man:") => {
"👩❤💋👨"
};
(":kiss_ww:") => {
"👩❤💋👩"
};
(":kissing:") => {
"😗"
};
(":kissing_cat:") => {
"😽"
};
(":kissing_closed_eyes:") => {
"😚"
};
(":kissing_heart:") => {
"😘"
};
(":kissing_smiling_eyes:") => {
"😙"
};
(":kiwi:") => {
"🥝"
};
(":knife:") => {
"🔪"
};
(":koala:") => {
"🐨"
};
(":koko:") => {
"🈁"
};
(":label:") => {
"🏷"
};
(":large_blue_diamond:") => {
"🔷"
};
(":large_orange_diamond:") => {
"🔶"
};
(":last_quarter_moon:") => {
"🌗"
};
(":last_quarter_moon_with_face:") => {
"🌜"
};
(":laughing:") => {
"😆"
};
(":leaves:") => {
"🍃"
};
(":ledger:") => {
"📒"
};
(":left_facing_fist:") => {
"🤛"
};
(":left_facing_fist_tone1:") => {
"🤛🏻"
};
(":left_facing_fist_tone2:") => {
"🤛🏼"
};
(":left_facing_fist_tone3:") => {
"🤛🏽"
};
(":left_facing_fist_tone4:") => {
"🤛🏾"
};
(":left_facing_fist_tone5:") => {
"🤛🏿"
};
(":left_luggage:") => {
"🛅"
};
(":left_right_arrow:") => {
"↔"
};
(":leftwards_arrow_with_hook:") => {
"↩"
};
(":lemon:") => {
"🍋"
};
(":leo:") => {
"♌"
};
(":leopard:") => {
"🐆"
};
(":level_slider:") => {
"🎚"
};
(":levitate:") => {
"🕴"
};
(":libra:") => {
"♎"
};
(":light_rail:") => {
"🚈"
};
(":link:") => {
"🔗"
};
(":lion_face:") => {
"🦁"
};
(":lips:") => {
"👄"
};
(":lipstick:") => {
"💄"
};
(":lizard:") => {
"🦎"
};
(":lock:") => {
"🔒"
};
(":lock_with_ink_pen:") => {
"🔏"
};
(":lollipop:") => {
"🍭"
};
(":loop:") => {
"➿"
};
(":loud_sound:") => {
"🔊"
};
(":loudspeaker:") => {
"📢"
};
(":love_hotel:") => {
"🏩"
};
(":love_letter:") => {
"💌"
};
(":love_you_gesture:") => {
"🤟"
};
(":love_you_gesture_tone1:") => {
"🤟🏻"
};
(":love_you_gesture_tone2:") => {
"🤟🏼"
};
(":love_you_gesture_tone3:") => {
"🤟🏽"
};
(":love_you_gesture_tone4:") => {
"🤟🏾"
};
(":love_you_gesture_tone5:") => {
"🤟🏿"
};
(":low_brightness:") => {
"🔅"
};
(":lying_face:") => {
"🤥"
};
(":m:") => {
"Ⓜ"
};
(":mag:") => {
"🔍"
};
(":mag_right:") => {
"🔎"
};
(":mage:") => {
"🧙"
};
(":mage_tone1:") => {
"🧙🏻"
};
(":mage_tone2:") => {
"🧙🏼"
};
(":mage_tone3:") => {
"🧙🏽"
};
(":mage_tone4:") => {
"🧙🏾"
};
(":mage_tone5:") => {
"🧙🏿"
};
(":mahjong:") => {
"🀄"
};
(":mailbox:") => {
"📫"
};
(":mailbox_closed:") => {
"📪"
};
(":mailbox_with_mail:") => {
"📬"
};
(":mailbox_with_no_mail:") => {
"📭"
};
(":male_sign:") => {
"♂"
};
(":man:") => {
"👨"
};
(":man_artist:") => {
"👨🎨"
};
(":man_artist_tone1:") => {
"👨🏻🎨"
};
(":man_artist_tone2:") => {
"👨🏼🎨"
};
(":man_artist_tone3:") => {
"👨🏽🎨"
};
(":man_artist_tone4:") => {
"👨🏾🎨"
};
(":man_artist_tone5:") => {
"👨🏿🎨"
};
(":man_astronaut:") => {
"👨🚀"
};
(":man_astronaut_tone1:") => {
"👨🏻🚀"
};
(":man_astronaut_tone2:") => {
"👨🏼🚀"
};
(":man_astronaut_tone3:") => {
"👨🏽🚀"
};
(":man_astronaut_tone4:") => {
"👨🏾🚀"
};
(":man_astronaut_tone5:") => {
"👨🏿🚀"
};
(":man_biking:") => {
"🚴♂"
};
(":man_biking_tone1:") => {
"🚴🏻♂"
};
(":man_biking_tone2:") => {
"🚴🏼♂"
};
(":man_biking_tone3:") => {
"🚴🏽♂"
};
(":man_biking_tone4:") => {
"🚴🏾♂"
};
(":man_biking_tone5:") => {
"🚴🏿♂"
};
(":man_bouncing_ball:") => {
"⛹♂"
};
(":man_bouncing_ball_tone1:") => {
"⛹🏻♂"
};
(":man_bouncing_ball_tone2:") => {
"⛹🏼♂"
};
(":man_bouncing_ball_tone3:") => {
"⛹🏽♂"
};
(":man_bouncing_ball_tone4:") => {
"⛹🏾♂"
};
(":man_bouncing_ball_tone5:") => {
"⛹🏿♂"
};
(":man_bowing:") => {
"🙇♂"
};
(":man_bowing_tone1:") => {
"🙇🏻♂"
};
(":man_bowing_tone2:") => {
"🙇🏼♂"
};
(":man_bowing_tone3:") => {
"🙇🏽♂"
};
(":man_bowing_tone4:") => {
"🙇🏾♂"
};
(":man_bowing_tone5:") => {
"🙇🏿♂"
};
(":man_cartwheeling:") => {
"🤸♂"
};
(":man_cartwheeling_tone1:") => {
"🤸🏻♂"
};
(":man_cartwheeling_tone2:") => {
"🤸🏼♂"
};
(":man_cartwheeling_tone3:") => {
"🤸🏽♂"
};
(":man_cartwheeling_tone4:") => {
"🤸🏾♂"
};
(":man_cartwheeling_tone5:") => {
"🤸🏿♂"
};
(":man_climbing:") => {
"🧗♂"
};
(":man_climbing_tone1:") => {
"🧗🏻♂"
};
(":man_climbing_tone2:") => {
"🧗🏼♂"
};
(":man_climbing_tone3:") => {
"🧗🏽♂"
};
(":man_climbing_tone4:") => {
"🧗🏾♂"
};
(":man_climbing_tone5:") => {
"🧗🏿♂"
};
(":man_construction_worker:") => {
"👷♂"
};
(":man_construction_worker_tone1:") => {
"👷🏻♂"
};
(":man_construction_worker_tone2:") => {
"👷🏼♂"
};
(":man_construction_worker_tone3:") => {
"👷🏽♂"
};
(":man_construction_worker_tone4:") => {
"👷🏾♂"
};
(":man_construction_worker_tone5:") => {
"👷🏿♂"
};
(":man_cook:") => {
"👨🍳"
};
(":man_cook_tone1:") => {
"👨🏻🍳"
};
(":man_cook_tone2:") => {
"👨🏼🍳"
};
(":man_cook_tone3:") => {
"👨🏽🍳"
};
(":man_cook_tone4:") => {
"👨🏾🍳"
};
(":man_cook_tone5:") => {
"👨🏿🍳"
};
(":man_dancing:") => {
"🕺"
};
(":man_dancing_tone1:") => {
"🕺🏻"
};
(":man_dancing_tone2:") => {
"🕺🏼"
};
(":man_dancing_tone3:") => {
"🕺🏽"
};
(":man_dancing_tone4:") => {
"🕺🏾"
};
(":man_dancing_tone5:") => {
"🕺🏿"
};
(":man_detective:") => {
"🕵♂"
};
(":man_detective_tone1:") => {
"🕵🏻♂"
};
(":man_detective_tone2:") => {
"🕵🏼♂"
};
(":man_detective_tone3:") => {
"🕵🏽♂"
};
(":man_detective_tone4:") => {
"🕵🏾♂"
};
(":man_detective_tone5:") => {
"🕵🏿♂"
};
(":man_elf:") => {
"🧝♂"
};
(":man_elf_tone1:") => {
"🧝🏻♂"
};
(":man_elf_tone2:") => {
"🧝🏼♂"
};
(":man_elf_tone3:") => {
"🧝🏽♂"
};
(":man_elf_tone4:") => {
"🧝🏾♂"
};
(":man_elf_tone5:") => {
"🧝🏿♂"
};
(":man_facepalming:") => {
"🤦♂"
};
(":man_facepalming_tone1:") => {
"🤦🏻♂"
};
(":man_facepalming_tone2:") => {
"🤦🏼♂"
};
(":man_facepalming_tone3:") => {
"🤦🏽♂"
};
(":man_facepalming_tone4:") => {
"🤦🏾♂"
};
(":man_facepalming_tone5:") => {
"🤦🏿♂"
};
(":man_factory_worker:") => {
"👨🏭"
};
(":man_factory_worker_tone1:") => {
"👨🏻🏭"
};
(":man_factory_worker_tone2:") => {
"👨🏼🏭"
};
(":man_factory_worker_tone3:") => {
"👨🏽🏭"
};
(":man_factory_worker_tone4:") => {
"👨🏾🏭"
};
(":man_factory_worker_tone5:") => {
"👨🏿🏭"
};
(":man_fairy:") => {
"🧚♂"
};
(":man_fairy_tone1:") => {
"🧚🏻♂"
};
(":man_fairy_tone2:") => {
"🧚🏼♂"
};
(":man_fairy_tone3:") => {
"🧚🏽♂"
};
(":man_fairy_tone4:") => {
"🧚🏾♂"
};
(":man_fairy_tone5:") => {
"🧚🏿♂"
};
(":man_farmer:") => {
"👨🌾"
};
(":man_farmer_tone1:") => {
"👨🏻🌾"
};
(":man_farmer_tone2:") => {
"👨🏼🌾"
};
(":man_farmer_tone3:") => {
"👨🏽🌾"
};
(":man_farmer_tone4:") => {
"👨🏾🌾"
};
(":man_farmer_tone5:") => {
"👨🏿🌾"
};
(":man_firefighter:") => {
"👨🚒"
};
(":man_firefighter_tone1:") => {
"👨🏻🚒"
};
(":man_firefighter_tone2:") => {
"👨🏼🚒"
};
(":man_firefighter_tone3:") => {
"👨🏽🚒"
};
(":man_firefighter_tone4:") => {
"👨🏾🚒"
};
(":man_firefighter_tone5:") => {
"👨🏿🚒"
};
(":man_frowning:") => {
"🙍♂"
};
(":man_frowning_tone1:") => {
"🙍🏻♂"
};
(":man_frowning_tone2:") => {
"🙍🏼♂"
};
(":man_frowning_tone3:") => {
"🙍🏽♂"
};
(":man_frowning_tone4:") => {
"🙍🏾♂"
};
(":man_frowning_tone5:") => {
"🙍🏿♂"
};
(":man_genie:") => {
"🧞♂"
};
(":man_gesturing_no:") => {
"🙅♂"
};
(":man_gesturing_no_tone1:") => {
"🙅🏻♂"
};
(":man_gesturing_no_tone2:") => {
"🙅🏼♂"
};
(":man_gesturing_no_tone3:") => {
"🙅🏽♂"
};
(":man_gesturing_no_tone4:") => {
"🙅🏾♂"
};
(":man_gesturing_no_tone5:") => {
"🙅🏿♂"
};
(":man_gesturing_ok:") => {
"🙆♂"
};
(":man_gesturing_ok_tone1:") => {
"🙆🏻♂"
};
(":man_gesturing_ok_tone2:") => {
"🙆🏼♂"
};
(":man_gesturing_ok_tone3:") => {
"🙆🏽♂"
};
(":man_gesturing_ok_tone4:") => {
"🙆🏾♂"
};
(":man_gesturing_ok_tone5:") => {
"🙆🏿♂"
};
(":man_getting_face_massage:") => {
"💆♂"
};
(":man_getting_face_massage_tone1:") => {
"💆🏻♂"
};
(":man_getting_face_massage_tone2:") => {
"💆🏼♂"
};
(":man_getting_face_massage_tone3:") => {
"💆🏽♂"
};
(":man_getting_face_massage_tone4:") => {
"💆🏾♂"
};
(":man_getting_face_massage_tone5:") => {
"💆🏿♂"
};
(":man_getting_haircut:") => {
"💇♂"
};
(":man_getting_haircut_tone1:") => {
"💇🏻♂"
};
(":man_getting_haircut_tone2:") => {
"💇🏼♂"
};
(":man_getting_haircut_tone3:") => {
"💇🏽♂"
};
(":man_getting_haircut_tone4:") => {
"💇🏾♂"
};
(":man_getting_haircut_tone5:") => {
"💇🏿♂"
};
(":man_golfing:") => {
"🏌♂"
};
(":man_golfing_tone1:") => {
"🏌🏻♂"
};
(":man_golfing_tone2:") => {
"🏌🏼♂"
};
(":man_golfing_tone3:") => {
"🏌🏽♂"
};
(":man_golfing_tone4:") => {
"🏌🏾♂"
};
(":man_golfing_tone5:") => {
"🏌🏿♂"
};
(":man_guard:") => {
"💂♂"
};
(":man_guard_tone1:") => {
"💂🏻♂"
};
(":man_guard_tone2:") => {
"💂🏼♂"
};
(":man_guard_tone3:") => {
"💂🏽♂"
};
(":man_guard_tone4:") => {
"💂🏾♂"
};
(":man_guard_tone5:") => {
"💂🏿♂"
};
(":man_health_worker:") => {
"👨⚕"
};
(":man_health_worker_tone1:") => {
"👨🏻⚕"
};
(":man_health_worker_tone2:") => {
"👨🏼⚕"
};
(":man_health_worker_tone3:") => {
"👨🏽⚕"
};
(":man_health_worker_tone4:") => {
"👨🏾⚕"
};
(":man_health_worker_tone5:") => {
"👨🏿⚕"
};
(":man_in_business_suit_levitating_tone1:") => {
"🕴🏻"
};
(":man_in_business_suit_levitating_tone2:") => {
"🕴🏼"
};
(":man_in_business_suit_levitating_tone3:") => {
"🕴🏽"
};
(":man_in_business_suit_levitating_tone4:") => {
"🕴🏾"
};
(":man_in_business_suit_levitating_tone5:") => {
"🕴🏿"
};
(":man_in_lotus_position:") => {
"🧘♂"
};
(":man_in_lotus_position_tone1:") => {
"🧘🏻♂"
};
(":man_in_lotus_position_tone2:") => {
"🧘🏼♂"
};
(":man_in_lotus_position_tone3:") => {
"🧘🏽♂"
};
(":man_in_lotus_position_tone4:") => {
"🧘🏾♂"
};
(":man_in_lotus_position_tone5:") => {
"🧘🏿♂"
};
(":man_in_steamy_room:") => {
"🧖♂"
};
(":man_in_steamy_room_tone1:") => {
"🧖🏻♂"
};
(":man_in_steamy_room_tone2:") => {
"🧖🏼♂"
};
(":man_in_steamy_room_tone3:") => {
"🧖🏽♂"
};
(":man_in_steamy_room_tone4:") => {
"🧖🏾♂"
};
(":man_in_steamy_room_tone5:") => {
"🧖🏿♂"
};
(":man_in_tuxedo:") => {
"🤵"
};
(":man_in_tuxedo_tone1:") => {
"🤵🏻"
};
(":man_in_tuxedo_tone2:") => {
"🤵🏼"
};
(":man_in_tuxedo_tone3:") => {
"🤵🏽"
};
(":man_in_tuxedo_tone4:") => {
"🤵🏾"
};
(":man_in_tuxedo_tone5:") => {
"🤵🏿"
};
(":man_judge:") => {
"👨⚖"
};
(":man_judge_tone1:") => {
"👨🏻⚖"
};
(":man_judge_tone2:") => {
"👨🏼⚖"
};
(":man_judge_tone3:") => {
"👨🏽⚖"
};
(":man_judge_tone4:") => {
"👨🏾⚖"
};
(":man_judge_tone5:") => {
"👨🏿⚖"
};
(":man_juggling:") => {
"🤹♂"
};
(":man_juggling_tone1:") => {
"🤹🏻♂"
};
(":man_juggling_tone2:") => {
"🤹🏼♂"
};
(":man_juggling_tone3:") => {
"🤹🏽♂"
};
(":man_juggling_tone4:") => {
"🤹🏾♂"
};
(":man_juggling_tone5:") => {
"🤹🏿♂"
};
(":man_lifting_weights:") => {
"🏋♂"
};
(":man_lifting_weights_tone1:") => {
"🏋🏻♂"
};
(":man_lifting_weights_tone2:") => {
"🏋🏼♂"
};
(":man_lifting_weights_tone3:") => {
"🏋🏽♂"
};
(":man_lifting_weights_tone4:") => {
"🏋🏾♂"
};
(":man_lifting_weights_tone5:") => {
"🏋🏿♂"
};
(":man_mage:") => {
"🧙♂"
};
(":man_mage_tone1:") => {
"🧙🏻♂"
};
(":man_mage_tone2:") => {
"🧙🏼♂"
};
(":man_mage_tone3:") => {
"🧙🏽♂"
};
(":man_mage_tone4:") => {
"🧙🏾♂"
};
(":man_mage_tone5:") => {
"🧙🏿♂"
};
(":man_mechanic:") => {
"👨🔧"
};
(":man_mechanic_tone1:") => {
"👨🏻🔧"
};
(":man_mechanic_tone2:") => {
"👨🏼🔧"
};
(":man_mechanic_tone3:") => {
"👨🏽🔧"
};
(":man_mechanic_tone4:") => {
"👨🏾🔧"
};
(":man_mechanic_tone5:") => {
"👨🏿🔧"
};
(":man_mountain_biking:") => {
"🚵♂"
};
(":man_mountain_biking_tone1:") => {
"🚵🏻♂"
};
(":man_mountain_biking_tone2:") => {
"🚵🏼♂"
};
(":man_mountain_biking_tone3:") => {
"🚵🏽♂"
};
(":man_mountain_biking_tone4:") => {
"🚵🏾♂"
};
(":man_mountain_biking_tone5:") => {
"🚵🏿♂"
};
(":man_office_worker:") => {
"👨💼"
};
(":man_office_worker_tone1:") => {
"👨🏻💼"
};
(":man_office_worker_tone2:") => {
"👨🏼💼"
};
(":man_office_worker_tone3:") => {
"👨🏽💼"
};
(":man_office_worker_tone4:") => {
"👨🏾💼"
};
(":man_office_worker_tone5:") => {
"👨🏿💼"
};
(":man_pilot:") => {
"👨✈"
};
(":man_pilot_tone1:") => {
"👨🏻✈"
};
(":man_pilot_tone2:") => {
"👨🏼✈"
};
(":man_pilot_tone3:") => {
"👨🏽✈"
};
(":man_pilot_tone4:") => {
"👨🏾✈"
};
(":man_pilot_tone5:") => {
"👨🏿✈"
};
(":man_playing_handball:") => {
"🤾♂"
};
(":man_playing_handball_tone1:") => {
"🤾🏻♂"
};
(":man_playing_handball_tone2:") => {
"🤾🏼♂"
};
(":man_playing_handball_tone3:") => {
"🤾🏽♂"
};
(":man_playing_handball_tone4:") => {
"🤾🏾♂"
};
(":man_playing_handball_tone5:") => {
"🤾🏿♂"
};
(":man_playing_water_polo:") => {
"🤽♂"
};
(":man_playing_water_polo_tone1:") => {
"🤽🏻♂"
};
(":man_playing_water_polo_tone2:") => {
"🤽🏼♂"
};
(":man_playing_water_polo_tone3:") => {
"🤽🏽♂"
};
(":man_playing_water_polo_tone4:") => {
"🤽🏾♂"
};
(":man_playing_water_polo_tone5:") => {
"🤽🏿♂"
};
(":man_police_officer:") => {
"👮♂"
};
(":man_police_officer_tone1:") => {
"👮🏻♂"
};
(":man_police_officer_tone2:") => {
"👮🏼♂"
};
(":man_police_officer_tone3:") => {
"👮🏽♂"
};
(":man_police_officer_tone4:") => {
"👮🏾♂"
};
(":man_police_officer_tone5:") => {
"👮🏿♂"
};
(":man_pouting:") => {
"🙎♂"
};
(":man_pouting_tone1:") => {
"🙎🏻♂"
};
(":man_pouting_tone2:") => {
"🙎🏼♂"
};
(":man_pouting_tone3:") => {
"🙎🏽♂"
};
(":man_pouting_tone4:") => {
"🙎🏾♂"
};
(":man_pouting_tone5:") => {
"🙎🏿♂"
};
(":man_raising_hand:") => {
"🙋♂"
};
(":man_raising_hand_tone1:") => {
"🙋🏻♂"
};
(":man_raising_hand_tone2:") => {
"🙋🏼♂"
};
(":man_raising_hand_tone3:") => {
"🙋🏽♂"
};
(":man_raising_hand_tone4:") => {
"🙋🏾♂"
};
(":man_raising_hand_tone5:") => {
"🙋🏿♂"
};
(":man_rowing_boat:") => {
"🚣♂"
};
(":man_rowing_boat_tone1:") => {
"🚣🏻♂"
};
(":man_rowing_boat_tone2:") => {
"🚣🏼♂"
};
(":man_rowing_boat_tone3:") => {
"🚣🏽♂"
};
(":man_rowing_boat_tone4:") => {
"🚣🏾♂"
};
(":man_rowing_boat_tone5:") => {
"🚣🏿♂"
};
(":man_running:") => {
"🏃♂"
};
(":man_running_tone1:") => {
"🏃🏻♂"
};
(":man_running_tone2:") => {
"🏃🏼♂"
};
(":man_running_tone3:") => {
"🏃🏽♂"
};
(":man_running_tone4:") => {
"🏃🏾♂"
};
(":man_running_tone5:") => {
"🏃🏿♂"
};
(":man_scientist:") => {
"👨🔬"
};
(":man_scientist_tone1:") => {
"👨🏻🔬"
};
(":man_scientist_tone2:") => {
"👨🏼🔬"
};
(":man_scientist_tone3:") => {
"👨🏽🔬"
};
(":man_scientist_tone4:") => {
"👨🏾🔬"
};
(":man_scientist_tone5:") => {
"👨🏿🔬"
};
(":man_shrugging:") => {
"🤷♂"
};
(":man_shrugging_tone1:") => {
"🤷🏻♂"
};
(":man_shrugging_tone2:") => {
"🤷🏼♂"
};
(":man_shrugging_tone3:") => {
"🤷🏽♂"
};
(":man_shrugging_tone4:") => {
"🤷🏾♂"
};
(":man_shrugging_tone5:") => {
"🤷🏿♂"
};
(":man_singer:") => {
"👨🎤"
};
(":man_singer_tone1:") => {
"👨🏻🎤"
};
(":man_singer_tone2:") => {
"👨🏼🎤"
};
(":man_singer_tone3:") => {
"👨🏽🎤"
};
(":man_singer_tone4:") => {
"👨🏾🎤"
};
(":man_singer_tone5:") => {
"👨🏿🎤"
};
(":man_student:") => {
"👨🎓"
};
(":man_student_tone1:") => {
"👨🏻🎓"
};
(":man_student_tone2:") => {
"👨🏼🎓"
};
(":man_student_tone3:") => {
"👨🏽🎓"
};
(":man_student_tone4:") => {
"👨🏾🎓"
};
(":man_student_tone5:") => {
"👨🏿🎓"
};
(":man_surfing:") => {
"🏄♂"
};
(":man_surfing_tone1:") => {
"🏄🏻♂"
};
(":man_surfing_tone2:") => {
"🏄🏼♂"
};
(":man_surfing_tone3:") => {
"🏄🏽♂"
};
(":man_surfing_tone4:") => {
"🏄🏾♂"
};
(":man_surfing_tone5:") => {
"🏄🏿♂"
};
(":man_swimming:") => {
"🏊♂"
};
(":man_swimming_tone1:") => {
"🏊🏻♂"
};
(":man_swimming_tone2:") => {
"🏊🏼♂"
};
(":man_swimming_tone3:") => {
"🏊🏽♂"
};
(":man_swimming_tone4:") => {
"🏊🏾♂"
};
(":man_swimming_tone5:") => {
"🏊🏿♂"
};
(":man_teacher:") => {
"👨🏫"
};
(":man_teacher_tone1:") => {
"👨🏻🏫"
};
(":man_teacher_tone2:") => {
"👨🏼🏫"
};
(":man_teacher_tone3:") => {
"👨🏽🏫"
};
(":man_teacher_tone4:") => {
"👨🏾🏫"
};
(":man_teacher_tone5:") => {
"👨🏿🏫"
};
(":man_technologist:") => {
"👨💻"
};
(":man_technologist_tone1:") => {
"👨🏻💻"
};
(":man_technologist_tone2:") => {
"👨🏼💻"
};
(":man_technologist_tone3:") => {
"👨🏽💻"
};
(":man_technologist_tone4:") => {
"👨🏾💻"
};
(":man_technologist_tone5:") => {
"👨🏿💻"
};
(":man_tipping_hand:") => {
"💁♂"
};
(":man_tipping_hand_tone1:") => {
"💁🏻♂"
};
(":man_tipping_hand_tone2:") => {
"💁🏼♂"
};
(":man_tipping_hand_tone3:") => {
"💁🏽♂"
};
(":man_tipping_hand_tone4:") => {
"💁🏾♂"
};
(":man_tipping_hand_tone5:") => {
"💁🏿♂"
};
(":man_tone1:") => {
"👨🏻"
};
(":man_tone2:") => {
"👨🏼"
};
(":man_tone3:") => {
"👨🏽"
};
(":man_tone4:") => {
"👨🏾"
};
(":man_tone5:") => {
"👨🏿"
};
(":man_vampire:") => {
"🧛♂"
};
(":man_vampire_tone1:") => {
"🧛🏻♂"
};
(":man_vampire_tone2:") => {
"🧛🏼♂"
};
(":man_vampire_tone3:") => {
"🧛🏽♂"
};
(":man_vampire_tone4:") => {
"🧛🏾♂"
};
(":man_vampire_tone5:") => {
"🧛🏿♂"
};
(":man_walking:") => {
"🚶♂"
};
(":man_walking_tone1:") => {
"🚶🏻♂"
};
(":man_walking_tone2:") => {
"🚶🏼♂"
};
(":man_walking_tone3:") => {
"🚶🏽♂"
};
(":man_walking_tone4:") => {
"🚶🏾♂"
};
(":man_walking_tone5:") => {
"🚶🏿♂"
};
(":man_wearing_turban:") => {
"👳♂"
};
(":man_wearing_turban_tone1:") => {
"👳🏻♂"
};
(":man_wearing_turban_tone2:") => {
"👳🏼♂"
};
(":man_wearing_turban_tone3:") => {
"👳🏽♂"
};
(":man_wearing_turban_tone4:") => {
"👳🏾♂"
};
(":man_wearing_turban_tone5:") => {
"👳🏿♂"
};
(":man_with_chinese_cap:") => {
"👲"
};
(":man_with_chinese_cap_tone1:") => {
"👲🏻"
};
(":man_with_chinese_cap_tone2:") => {
"👲🏼"
};
(":man_with_chinese_cap_tone3:") => {
"👲🏽"
};
(":man_with_chinese_cap_tone4:") => {
"👲🏾"
};
(":man_with_chinese_cap_tone5:") => {
"👲🏿"
};
(":man_zombie:") => {
"🧟♂"
};
(":mans_shoe:") => {
"👞"
};
(":map:") => {
"🗺"
};
(":maple_leaf:") => {
"🍁"
};
(":martial_arts_uniform:") => {
"🥋"
};
(":mask:") => {
"😷"
};
(":meat_on_bone:") => {
"🍖"
};
(":medal:") => {
"🏅"
};
(":medical_symbol:") => {
"⚕"
};
(":mega:") => {
"📣"
};
(":melon:") => {
"🍈"
};
(":men_with_bunny_ears_partying:") => {
"👯♂"
};
(":men_wrestling:") => {
"🤼♂"
};
(":menorah:") => {
"🕎"
};
(":mens:") => {
"🚹"
};
(":mermaid:") => {
"🧜♀"
};
(":mermaid_tone1:") => {
"🧜🏻♀"
};
(":mermaid_tone2:") => {
"🧜🏼♀"
};
(":mermaid_tone3:") => {
"🧜🏽♀"
};
(":mermaid_tone4:") => {
"🧜🏾♀"
};
(":mermaid_tone5:") => {
"🧜🏿♀"
};
(":merman:") => {
"🧜♂"
};
(":merman_tone1:") => {
"🧜🏻♂"
};
(":merman_tone2:") => {
"🧜🏼♂"
};
(":merman_tone3:") => {
"🧜🏽♂"
};
(":merman_tone4:") => {
"🧜🏾♂"
};
(":merman_tone5:") => {
"🧜🏿♂"
};
(":merperson:") => {
"🧜"
};
(":merperson_tone1:") => {
"🧜🏻"
};
(":merperson_tone2:") => {
"🧜🏼"
};
(":merperson_tone3:") => {
"🧜🏽"
};
(":merperson_tone4:") => {
"🧜🏾"
};
(":merperson_tone5:") => {
"🧜🏿"
};
(":metal:") => {
"🤘"
};
(":metal_tone1:") => {
"🤘🏻"
};
(":metal_tone2:") => {
"🤘🏼"
};
(":metal_tone3:") => {
"🤘🏽"
};
(":metal_tone4:") => {
"🤘🏾"
};
(":metal_tone5:") => {
"🤘🏿"
};
(":metro:") => {
"🚇"
};
(":microphone2:") => {
"🎙"
};
(":microphone:") => {
"🎤"
};
(":microscope:") => {
"🔬"
};
(":middle_finger:") => {
"🖕"
};
(":middle_finger_tone1:") => {
"🖕🏻"
};
(":middle_finger_tone2:") => {
"🖕🏼"
};
(":middle_finger_tone3:") => {
"🖕🏽"
};
(":middle_finger_tone4:") => {
"🖕🏾"
};
(":middle_finger_tone5:") => {
"🖕🏿"
};
(":military_medal:") => {
"🎖"
};
(":milk:") => {
"🥛"
};
(":milky_way:") => {
"🌌"
};
(":minibus:") => {
"🚐"
};
(":minidisc:") => {
"💽"
};
(":mobile_phone_off:") => {
"📴"
};
(":money_mouth:") => {
"🤑"
};
(":money_with_wings:") => {
"💸"
};
(":moneybag:") => {
"💰"
};
(":monkey:") => {
"🐒"
};
(":monkey_face:") => {
"🐵"
};
(":monorail:") => {
"🚝"
};
(":mortar_board:") => {
"🎓"
};
(":mosque:") => {
"🕌"
};
(":motor_scooter:") => {
"🛵"
};
(":motorboat:") => {
"🛥"
};
(":motorcycle:") => {
"🏍"
};
(":motorway:") => {
"🛣"
};
(":mount_fuji:") => {
"🗻"
};
(":mountain:") => {
"⛰"
};
(":mountain_cableway:") => {
"🚠"
};
(":mountain_railway:") => {
"🚞"
};
(":mountain_snow:") => {
"🏔"
};
(":mouse2:") => {
"🐁"
};
(":mouse:") => {
"🐭"
};
(":mouse_three_button:") => {
"🖱"
};
(":movie_camera:") => {
"🎥"
};
(":moyai:") => {
"🗿"
};
(":mrs_claus:") => {
"🤶"
};
(":mrs_claus_tone1:") => {
"🤶🏻"
};
(":mrs_claus_tone2:") => {
"🤶🏼"
};
(":mrs_claus_tone3:") => {
"🤶🏽"
};
(":mrs_claus_tone4:") => {
"🤶🏾"
};
(":mrs_claus_tone5:") => {
"🤶🏿"
};
(":muscle:") => {
"💪"
};
(":muscle_tone1:") => {
"💪🏻"
};
(":muscle_tone2:") => {
"💪🏼"
};
(":muscle_tone3:") => {
"💪🏽"
};
(":muscle_tone4:") => {
"💪🏾"
};
(":muscle_tone5:") => {
"💪🏿"
};
(":mushroom:") => {
"🍄"
};
(":musical_keyboard:") => {
"🎹"
};
(":musical_note:") => {
"🎵"
};
(":musical_score:") => {
"🎼"
};
(":mute:") => {
"🔇"
};
(":nail_care:") => {
"💅"
};
(":nail_care_tone1:") => {
"💅🏻"
};
(":nail_care_tone2:") => {
"💅🏼"
};
(":nail_care_tone3:") => {
"💅🏽"
};
(":nail_care_tone4:") => {
"💅🏾"
};
(":nail_care_tone5:") => {
"💅🏿"
};
(":name_badge:") => {
"📛"
};
(":nauseated_face:") => {
"🤢"
};
(":necktie:") => {
"👔"
};
(":negative_squared_cross_mark:") => {
"❎"
};
(":nerd:") => {
"🤓"
};
(":neutral_face:") => {
"😐"
};
(":new:") => {
"🆕"
};
(":new_moon:") => {
"🌑"
};
(":new_moon_with_face:") => {
"🌚"
};
(":newspaper2:") => {
"🗞"
};
(":newspaper:") => {
"📰"
};
(":ng:") => {
"🆖"
};
(":night_with_stars:") => {
"🌃"
};
(":nine:") => {
"9⃣"
};
(":no_bell:") => {
"🔕"
};
(":no_bicycles:") => {
"🚳"
};
(":no_entry:") => {
"⛔"
};
(":no_entry_sign:") => {
"🚫"
};
(":no_mobile_phones:") => {
"📵"
};
(":no_mouth:") => {
"😶"
};
(":no_pedestrians:") => {
"🚷"
};
(":no_smoking:") => {
"🚭"
};
(":non-potable_water:") => {
"🚱"
};
(":nose:") => {
"👃"
};
(":nose_tone1:") => {
"👃🏻"
};
(":nose_tone2:") => {
"👃🏼"
};
(":nose_tone3:") => {
"👃🏽"
};
(":nose_tone4:") => {
"👃🏾"
};
(":nose_tone5:") => {
"👃🏿"
};
(":notebook:") => {
"📓"
};
(":notebook_with_decorative_cover:") => {
"📔"
};
(":notepad_spiral:") => {
"🗒"
};
(":notes:") => {
"🎶"
};
(":nut_and_bolt:") => {
"🔩"
};
(":o2:") => {
"🅾"
};
(":o:") => {
"⭕"
};
(":ocean:") => {
"🌊"
};
(":octagonal_sign:") => {
"🛑"
};
(":octopus:") => {
"🐙"
};
(":oden:") => {
"🍢"
};
(":office:") => {
"🏢"
};
(":oil:") => {
"🛢"
};
(":ok:") => {
"🆗"
};
(":ok_hand:") => {
"👌"
};
(":ok_hand_tone1:") => {
"👌🏻"
};
(":ok_hand_tone2:") => {
"👌🏼"
};
(":ok_hand_tone3:") => {
"👌🏽"
};
(":ok_hand_tone4:") => {
"👌🏾"
};
(":ok_hand_tone5:") => {
"👌🏿"
};
(":older_adult:") => {
"🧓"
};
(":older_adult_tone1:") => {
"🧓🏻"
};
(":older_adult_tone2:") => {
"🧓🏼"
};
(":older_adult_tone3:") => {
"🧓🏽"
};
(":older_adult_tone4:") => {
"🧓🏾"
};
(":older_adult_tone5:") => {
"🧓🏿"
};
(":older_man:") => {
"👴"
};
(":older_man_tone1:") => {
"👴🏻"
};
(":older_man_tone2:") => {
"👴🏼"
};
(":older_man_tone3:") => {
"👴🏽"
};
(":older_man_tone4:") => {
"👴🏾"
};
(":older_man_tone5:") => {
"👴🏿"
};
(":older_woman:") => {
"👵"
};
(":older_woman_tone1:") => {
"👵🏻"
};
(":older_woman_tone2:") => {
"👵🏼"
};
(":older_woman_tone3:") => {
"👵🏽"
};
(":older_woman_tone4:") => {
"👵🏾"
};
(":older_woman_tone5:") => {
"👵🏿"
};
(":om_symbol:") => {
"🕉"
};
(":on:") => {
"🔛"
};
(":oncoming_automobile:") => {
"🚘"
};
(":oncoming_bus:") => {
"🚍"
};
(":oncoming_police_car:") => {
"🚔"
};
(":oncoming_taxi:") => {
"🚖"
};
(":one:") => {
"1⃣"
};
(":open_file_folder:") => {
"📂"
};
(":open_hands:") => {
"👐"
};
(":open_hands_tone1:") => {
"👐🏻"
};
(":open_hands_tone2:") => {
"👐🏼"
};
(":open_hands_tone3:") => {
"👐🏽"
};
(":open_hands_tone4:") => {
"👐🏾"
};
(":open_hands_tone5:") => {
"👐🏿"
};
(":open_mouth:") => {
"😮"
};
(":ophiuchus:") => {
"⛎"
};
(":orange_book:") => {
"📙"
};
(":orange_heart:") => {
"🧡"
};
(":orthodox_cross:") => {
"☦"
};
(":outbox_tray:") => {
"📤"
};
(":owl:") => {
"🦉"
};
(":ox:") => {
"🐂"
};
(":package:") => {
"📦"
};
(":page_facing_up:") => {
"📄"
};
(":page_with_curl:") => {
"📃"
};
(":pager:") => {
"📟"
};
(":paintbrush:") => {
"🖌"
};
(":palm_tree:") => {
"🌴"
};
(":palms_up_together:") => {
"🤲"
};
(":palms_up_together_tone1:") => {
"🤲🏻"
};
(":palms_up_together_tone2:") => {
"🤲🏼"
};
(":palms_up_together_tone3:") => {
"🤲🏽"
};
(":palms_up_together_tone4:") => {
"🤲🏾"
};
(":palms_up_together_tone5:") => {
"🤲🏿"
};
(":pancakes:") => {
"🥞"
};
(":panda_face:") => {
"🐼"
};
(":paperclip:") => {
"📎"
};
(":paperclips:") => {
"🖇"
};
(":park:") => {
"🏞"
};
(":parking:") => {
"🅿"
};
(":part_alternation_mark:") => {
"〽"
};
(":partly_sunny:") => {
"⛅"
};
(":passport_control:") => {
"🛂"
};
(":pause_button:") => {
"⏸"
};
(":peace:") => {
"☮"
};
(":peach:") => {
"🍑"
};
(":peanuts:") => {
"🥜"
};
(":pear:") => {
"🍐"
};
(":pen_ballpoint:") => {
"🖊"
};
(":pen_fountain:") => {
"🖋"
};
(":pencil2:") => {
"✏"
};
(":pencil:") => {
"📝"
};
(":penguin:") => {
"🐧"
};
(":pensive:") => {
"😔"
};
(":people_with_bunny_ears_partying:") => {
"👯"
};
(":people_wrestling:") => {
"🤼"
};
(":performing_arts:") => {
"🎭"
};
(":persevere:") => {
"😣"
};
(":person_biking:") => {
"🚴"
};
(":person_biking_tone1:") => {
"🚴🏻"
};
(":person_biking_tone2:") => {
"🚴🏼"
};
(":person_biking_tone3:") => {
"🚴🏽"
};
(":person_biking_tone4:") => {
"🚴🏾"
};
(":person_biking_tone5:") => {
"🚴🏿"
};
(":person_bouncing_ball:") => {
"⛹"
};
(":person_bouncing_ball_tone1:") => {
"⛹🏻"
};
(":person_bouncing_ball_tone2:") => {
"⛹🏼"
};
(":person_bouncing_ball_tone3:") => {
"⛹🏽"
};
(":person_bouncing_ball_tone4:") => {
"⛹🏾"
};
(":person_bouncing_ball_tone5:") => {
"⛹🏿"
};
(":person_bowing:") => {
"🙇"
};
(":person_bowing_tone1:") => {
"🙇🏻"
};
(":person_bowing_tone2:") => {
"🙇🏼"
};
(":person_bowing_tone3:") => {
"🙇🏽"
};
(":person_bowing_tone4:") => {
"🙇🏾"
};
(":person_bowing_tone5:") => {
"🙇🏿"
};
(":person_climbing:") => {
"🧗"
};
(":person_climbing_tone1:") => {
"🧗🏻"
};
(":person_climbing_tone2:") => {
"🧗🏼"
};
(":person_climbing_tone3:") => {
"🧗🏽"
};
(":person_climbing_tone4:") => {
"🧗🏾"
};
(":person_climbing_tone5:") => {
"🧗🏿"
};
(":person_doing_cartwheel:") => {
"🤸"
};
(":person_doing_cartwheel_tone1:") => {
"🤸🏻"
};
(":person_doing_cartwheel_tone2:") => {
"🤸🏼"
};
(":person_doing_cartwheel_tone3:") => {
"🤸🏽"
};
(":person_doing_cartwheel_tone4:") => {
"🤸🏾"
};
(":person_doing_cartwheel_tone5:") => {
"🤸🏿"
};
(":person_facepalming:") => {
"🤦"
};
(":person_facepalming_tone1:") => {
"🤦🏻"
};
(":person_facepalming_tone2:") => {
"🤦🏼"
};
(":person_facepalming_tone3:") => {
"🤦🏽"
};
(":person_facepalming_tone4:") => {
"🤦🏾"
};
(":person_facepalming_tone5:") => {
"🤦🏿"
};
(":person_fencing:") => {
"🤺"
};
(":person_frowning:") => {
"🙍"
};
(":person_frowning_tone1:") => {
"🙍🏻"
};
(":person_frowning_tone2:") => {
"🙍🏼"
};
(":person_frowning_tone3:") => {
"🙍🏽"
};
(":person_frowning_tone4:") => {
"🙍🏾"
};
(":person_frowning_tone5:") => {
"🙍🏿"
};
(":person_gesturing_no:") => {
"🙅"
};
(":person_gesturing_no_tone1:") => {
"🙅🏻"
};
(":person_gesturing_no_tone2:") => {
"🙅🏼"
};
(":person_gesturing_no_tone3:") => {
"🙅🏽"
};
(":person_gesturing_no_tone4:") => {
"🙅🏾"
};
(":person_gesturing_no_tone5:") => {
"🙅🏿"
};
(":person_gesturing_ok:") => {
"����"
};
(":person_gesturing_ok_tone1:") => {
"🙆🏻"
};
(":person_gesturing_ok_tone2:") => {
"🙆🏼"
};
(":person_gesturing_ok_tone3:") => {
"🙆🏽"
};
(":person_gesturing_ok_tone4:") => {
"🙆🏾"
};
(":person_gesturing_ok_tone5:") => {
"🙆🏿"
};
(":person_getting_haircut:") => {
"💇"
};
(":person_getting_haircut_tone1:") => {
"💇🏻"
};
(":person_getting_haircut_tone2:") => {
"💇🏼"
};
(":person_getting_haircut_tone3:") => {
"💇🏽"
};
(":person_getting_haircut_tone4:") => {
"💇🏾"
};
(":person_getting_haircut_tone5:") => {
"💇🏿"
};
(":person_getting_massage:") => {
"💆"
};
(":person_getting_massage_tone1:") => {
"💆🏻"
};
(":person_getting_massage_tone2:") => {
"💆🏼"
};
(":person_getting_massage_tone3:") => {
"💆🏽"
};
(":person_getting_massage_tone4:") => {
"💆🏾"
};
(":person_getting_massage_tone5:") => {
"💆🏿"
};
(":person_golfing:") => {
"🏌"
};
(":person_golfing_tone1:") => {
"🏌🏻"
};
(":person_golfing_tone2:") => {
"🏌🏼"
};
(":person_golfing_tone3:") => {
"🏌🏽"
};
(":person_golfing_tone4:") => {
"🏌🏾"
};
(":person_golfing_tone5:") => {
"🏌🏿"
};
(":person_in_bed_tone1:") => {
"🛌🏻"
};
(":person_in_bed_tone2:") => {
"🛌🏼"
};
(":person_in_bed_tone3:") => {
"🛌🏽"
};
(":person_in_bed_tone4:") => {
"🛌🏾"
};
(":person_in_bed_tone5:") => {
"🛌🏿"
};
(":person_in_lotus_position:") => {
"🧘"
};
(":person_in_lotus_position_tone1:") => {
"🧘🏻"
};
(":person_in_lotus_position_tone2:") => {
"🧘🏼"
};
(":person_in_lotus_position_tone3:") => {
"🧘🏽"
};
(":person_in_lotus_position_tone4:") => {
"🧘🏾"
};
(":person_in_lotus_position_tone5:") => {
"🧘🏿"
};
(":person_in_steamy_room:") => {
"🧖"
};
(":person_in_steamy_room_tone1:") => {
"🧖🏻"
};
(":person_in_steamy_room_tone2:") => {
"🧖🏼"
};
(":person_in_steamy_room_tone3:") => {
"🧖🏽"
};
(":person_in_steamy_room_tone4:") => {
"🧖🏾"
};
(":person_in_steamy_room_tone5:") => {
"🧖🏿"
};
(":person_juggling:") => {
"🤹"
};
(":person_juggling_tone1:") => {
"🤹🏻"
};
(":person_juggling_tone2:") => {
"🤹🏼"
};
(":person_juggling_tone3:") => {
"🤹🏽"
};
(":person_juggling_tone4:") => {
"🤹🏾"
};
(":person_juggling_tone5:") => {
"🤹🏿"
};
(":person_lifting_weights:") => {
"🏋"
};
(":person_lifting_weights_tone1:") => {
"🏋🏻"
};
(":person_lifting_weights_tone2:") => {
"🏋🏼"
};
(":person_lifting_weights_tone3:") => {
"🏋🏽"
};
(":person_lifting_weights_tone4:") => {
"🏋🏾"
};
(":person_lifting_weights_tone5:") => {
"🏋🏿"
};
(":person_mountain_biking:") => {
"🚵"
};
(":person_mountain_biking_tone1:") => {
"🚵🏻"
};
(":person_mountain_biking_tone2:") => {
"🚵🏼"
};
(":person_mountain_biking_tone3:") => {
"🚵🏽"
};
(":person_mountain_biking_tone4:") => {
"🚵🏾"
};
(":person_mountain_biking_tone5:") => {
"🚵🏿"
};
(":person_playing_handball:") => {
"🤾"
};
(":person_playing_handball_tone1:") => {
"🤾🏻"
};
(":person_playing_handball_tone2:") => {
"🤾🏼"
};
(":person_playing_handball_tone3:") => {
"🤾🏽"
};
(":person_playing_handball_tone4:") => {
"🤾🏾"
};
(":person_playing_handball_tone5:") => {
"🤾🏿"
};
(":person_playing_water_polo:") => {
"🤽"
};
(":person_playing_water_polo_tone1:") => {
"🤽🏻"
};
(":person_playing_water_polo_tone2:") => {
"🤽🏼"
};
(":person_playing_water_polo_tone3:") => {
"🤽🏽"
};
(":person_playing_water_polo_tone4:") => {
"🤽🏾"
};
(":person_playing_water_polo_tone5:") => {
"🤽🏿"
};
(":person_pouting:") => {
"🙎"
};
(":person_pouting_tone1:") => {
"🙎🏻"
};
(":person_pouting_tone2:") => {
"🙎🏼"
};
(":person_pouting_tone3:") => {
"🙎🏽"
};
(":person_pouting_tone4:") => {
"🙎🏾"
};
(":person_pouting_tone5:") => {
"🙎🏿"
};
(":person_raising_hand:") => {
"🙋"
};
(":person_raising_hand_tone1:") => {
"🙋🏻"
};
(":person_raising_hand_tone2:") => {
"🙋🏼"
};
(":person_raising_hand_tone3:") => {
"🙋🏽"
};
(":person_raising_hand_tone4:") => {
"🙋🏾"
};
(":person_raising_hand_tone5:") => {
"🙋🏿"
};
(":person_rowing_boat:") => {
"🚣"
};
(":person_rowing_boat_tone1:") => {
"🚣🏻"
};
(":person_rowing_boat_tone2:") => {
"🚣🏼"
};
(":person_rowing_boat_tone3:") => {
"🚣🏽"
};
(":person_rowing_boat_tone4:") => {
"🚣🏾"
};
(":person_rowing_boat_tone5:") => {
"🚣🏿"
};
(":person_running:") => {
"🏃"
};
(":person_running_tone1:") => {
"🏃🏻"
};
(":person_running_tone2:") => {
"🏃🏼"
};
(":person_running_tone3:") => {
"🏃🏽"
};
(":person_running_tone4:") => {
"🏃🏾"
};
(":person_running_tone5:") => {
"🏃🏿"
};
(":person_shrugging:") => {
"🤷"
};
(":person_shrugging_tone1:") => {
"🤷🏻"
};
(":person_shrugging_tone2:") => {
"🤷🏼"
};
(":person_shrugging_tone3:") => {
"🤷🏽"
};
(":person_shrugging_tone4:") => {
"🤷🏾"
};
(":person_shrugging_tone5:") => {
"🤷🏿"
};
(":person_surfing:") => {
"🏄"
};
(":person_surfing_tone1:") => {
"🏄🏻"
};
(":person_surfing_tone2:") => {
"🏄🏼"
};
(":person_surfing_tone3:") => {
"🏄🏽"
};
(":person_surfing_tone4:") => {
"🏄🏾"
};
(":person_surfing_tone5:") => {
"🏄🏿"
};
(":person_swimming:") => {
"🏊"
};
(":person_swimming_tone1:") => {
"🏊🏻"
};
(":person_swimming_tone2:") => {
"🏊🏼"
};
(":person_swimming_tone3:") => {
"🏊🏽"
};
(":person_swimming_tone4:") => {
"🏊🏾"
};
(":person_swimming_tone5:") => {
"🏊🏿"
};
(":person_tipping_hand:") => {
"💁"
};
(":person_tipping_hand_tone1:") => {
"💁🏻"
};
(":person_tipping_hand_tone2:") => {
"💁🏼"
};
(":person_tipping_hand_tone3:") => {
"💁🏽"
};
(":person_tipping_hand_tone4:") => {
"💁🏾"
};
(":person_tipping_hand_tone5:") => {
"💁🏿"
};
(":person_walking:") => {
"🚶"
};
(":person_walking_tone1:") => {
"🚶🏻"
};
(":person_walking_tone2:") => {
"🚶🏼"
};
(":person_walking_tone3:") => {
"🚶🏽"
};
(":person_walking_tone4:") => {
"🚶🏾"
};
(":person_walking_tone5:") => {
"🚶🏿"
};
(":person_wearing_turban:") => {
"👳"
};
(":person_wearing_turban_tone1:") => {
"👳🏻"
};
(":person_wearing_turban_tone2:") => {
"👳🏼"
};
(":person_wearing_turban_tone3:") => {
"👳🏽"
};
(":person_wearing_turban_tone4:") => {
"👳🏾"
};
(":person_wearing_turban_tone5:") => {
"👳🏿"
};
(":pick:") => {
"⛏"
};
(":pie:") => {
"🥧"
};
(":pig2:") => {
"🐖"
};
(":pig:") => {
"🐷"
};
(":pig_nose:") => {
"🐽"
};
(":pill:") => {
"💊"
};
(":pineapple:") => {
"🍍"
};
(":ping_pong:") => {
"🏓"
};
(":pisces:") => {
"♓"
};
(":pizza:") => {
"🍕"
};
(":place_of_worship:") => {
"🛐"
};
(":play_pause:") => {
"⏯"
};
(":point_down:") => {
"👇"
};
(":point_down_tone1:") => {
"👇🏻"
};
(":point_down_tone2:") => {
"👇🏼"
};
(":point_down_tone3:") => {
"👇🏽"
};
(":point_down_tone4:") => {
"👇🏾"
};
(":point_down_tone5:") => {
"👇🏿"
};
(":point_left:") => {
"👈"
};
(":point_left_tone1:") => {
"👈🏻"
};
(":point_left_tone2:") => {
"👈🏼"
};
(":point_left_tone3:") => {
"👈🏽"
};
(":point_left_tone4:") => {
"👈🏾"
};
(":point_left_tone5:") => {
"👈🏿"
};
(":point_right:") => {
"👉"
};
(":point_right_tone1:") => {
"👉🏻"
};
(":point_right_tone2:") => {
"👉🏼"
};
(":point_right_tone3:") => {
"👉🏽"
};
(":point_right_tone4:") => {
"👉🏾"
};
(":point_right_tone5:") => {
"👉🏿"
};
(":point_up:") => {
"☝"
};
(":point_up_2:") => {
"👆"
};
(":point_up_2_tone1:") => {
"👆🏻"
};
(":point_up_2_tone2:") => {
"👆🏼"
};
(":point_up_2_tone3:") => {
"👆🏽"
};
(":point_up_2_tone4:") => {
"👆🏾"
};
(":point_up_2_tone5:") => {
"👆🏿"
};
(":point_up_tone1:") => {
"☝🏻"
};
(":point_up_tone2:") => {
"☝🏼"
};
(":point_up_tone3:") => {
"☝🏽"
};
(":point_up_tone4:") => {
"☝🏾"
};
(":point_up_tone5:") => {
"☝🏿"
};
(":police_car:") => {
"🚓"
};
(":police_officer:") => {
"👮"
};
(":police_officer_tone1:") => {
"👮🏻"
};
(":police_officer_tone2:") => {
"👮🏼"
};
(":police_officer_tone3:") => {
"👮🏽"
};
(":police_officer_tone4:") => {
"👮🏾"
};
(":police_officer_tone5:") => {
"👮🏿"
};
(":poodle:") => {
"🐩"
};
(":poop:") => {
"💩"
};
(":popcorn:") => {
"🍿"
};
(":post_office:") => {
"🏣"
};
(":postal_horn:") => {
"📯"
};
(":postbox:") => {
"📮"
};
(":potable_water:") => {
"🚰"
};
(":potato:") => {
"🥔"
};
(":pouch:") => {
"👝"
};
(":poultry_leg:") => {
"🍗"
};
(":pound:") => {
"💷"
};
(":pound_symbol:") => {
"#"
};
(":pouting_cat:") => {
"😾"
};
(":pray:") => {
"🙏"
};
(":pray_tone1:") => {
"🙏🏻"
};
(":pray_tone2:") => {
"🙏🏼"
};
(":pray_tone3:") => {
"🙏🏽"
};
(":pray_tone4:") => {
"🙏🏾"
};
(":pray_tone5:") => {
"🙏🏿"
};
(":prayer_beads:") => {
"📿"
};
(":pregnant_woman:") => {
"🤰"
};
(":pregnant_woman_tone1:") => {
"🤰🏻"
};
(":pregnant_woman_tone2:") => {
"🤰🏼"
};
(":pregnant_woman_tone3:") => {
"🤰🏽"
};
(":pregnant_woman_tone4:") => {
"🤰🏾"
};
(":pregnant_woman_tone5:") => {
"🤰🏿"
};
(":pretzel:") => {
"🥨"
};
(":prince:") => {
"🤴"
};
(":prince_tone1:") => {
"🤴🏻"
};
(":prince_tone2:") => {
"🤴🏼"
};
(":prince_tone3:") => {
"🤴🏽"
};
(":prince_tone4:") => {
"🤴🏾"
};
(":prince_tone5:") => {
"🤴🏿"
};
(":princess:") => {
"👸"
};
(":princess_tone1:") => {
"👸🏻"
};
(":princess_tone2:") => {
"👸🏼"
};
(":princess_tone3:") => {
"👸🏽"
};
(":princess_tone4:") => {
"👸🏾"
};
(":princess_tone5:") => {
"👸🏿"
};
(":printer:") => {
"🖨"
};
(":projector:") => {
"📽"
};
(":punch:") => {
"👊"
};
(":punch_tone1:") => {
"👊🏻"
};
(":punch_tone2:") => {
"👊🏼"
};
(":punch_tone3:") => {
"👊🏽"
};
(":punch_tone4:") => {
"👊🏾"
};
(":punch_tone5:") => {
"👊🏿"
};
(":purple_heart:") => {
"💜"
};
(":purse:") => {
"👛"
};
(":pushpin:") => {
"📌"
};
(":put_litter_in_its_place:") => {
"🚮"
};
(":question:") => {
"❓"
};
(":rabbit2:") => {
"🐇"
};
(":rabbit:") => {
"🐰"
};
(":race_car:") => {
"🏎"
};
(":racehorse:") => {
"🐎"
};
(":radio:") => {
"📻"
};
(":radio_button:") => {
"🔘"
};
(":radioactive:") => {
"☢"
};
(":rage:") => {
"😡"
};
(":railway_car:") => {
"🚃"
};
(":railway_track:") => {
"🛤"
};
(":rainbow:") => {
"🌈"
};
(":rainbow_flag:") => {
"🏳🌈"
};
(":raised_back_of_hand:") => {
"🤚"
};
(":raised_back_of_hand_tone1:") => {
"🤚🏻"
};
(":raised_back_of_hand_tone2:") => {
"🤚🏼"
};
(":raised_back_of_hand_tone3:") => {
"🤚🏽"
};
(":raised_back_of_hand_tone4:") => {
"🤚🏾"
};
(":raised_back_of_hand_tone5:") => {
"🤚🏿"
};
(":raised_hand:") => {
"✋"
};
(":raised_hand_tone1:") => {
"✋����"
};
(":raised_hand_tone2:") => {
"✋🏼"
};
(":raised_hand_tone3:") => {
"✋🏽"
};
(":raised_hand_tone4:") => {
"✋🏾"
};
(":raised_hand_tone5:") => {
"✋🏿"
};
(":raised_hands:") => {
"🙌"
};
(":raised_hands_tone1:") => {
"🙌🏻"
};
(":raised_hands_tone2:") => {
"🙌🏼"
};
(":raised_hands_tone3:") => {
"🙌🏽"
};
(":raised_hands_tone4:") => {
"🙌🏾"
};
(":raised_hands_tone5:") => {
"🙌🏿"
};
(":ram:") => {
"🐏"
};
(":ramen:") => {
"🍜"
};
(":rat:") => {
"🐀"
};
(":record_button:") => {
"⏺"
};
(":recycle:") => {
"♻"
};
(":red_car:") => {
"🚗"
};
(":red_circle:") => {
"🔴"
};
(":regional_indicator_a:") => {
"🇦"
};
(":regional_indicator_b:") => {
"🇧"
};
(":regional_indicator_c:") => {
"🇨"
};
(":regional_indicator_d:") => {
"🇩"
};
(":regional_indicator_e:") => {
"🇪"
};
(":regional_indicator_f:") => {
"🇫"
};
(":regional_indicator_g:") => {
"🇬"
};
(":regional_indicator_h:") => {
"🇭"
};
(":regional_indicator_i:") => {
"🇮"
};
(":regional_indicator_j:") => {
"🇯"
};
(":regional_indicator_k:") => {
"🇰"
};
(":regional_indicator_l:") => {
"🇱"
};
(":regional_indicator_m:") => {
"🇲"
};
(":regional_indicator_n:") => {
"🇳"
};
(":regional_indicator_o:") => {
"🇴"
};
(":regional_indicator_p:") => {
"🇵"
};
(":regional_indicator_q:") => {
"🇶"
};
(":regional_indicator_r:") => {
"🇷"
};
(":regional_indicator_s:") => {
"🇸"
};
(":regional_indicator_t:") => {
"🇹"
};
(":regional_indicator_u:") => {
"🇺"
};
(":regional_indicator_v:") => {
"🇻"
};
(":regional_indicator_w:") => {
"🇼"
};
(":regional_indicator_x:") => {
"🇽"
};
(":regional_indicator_y:") => {
"🇾"
};
(":regional_indicator_z:") => {
"🇿"
};
(":registered:") => {
"®"
};
(":relaxed:") => {
"☺"
};
(":relieved:") => {
"😌"
};
(":reminder_ribbon:") => {
"🎗"
};
(":repeat:") => {
"🔁"
};
(":repeat_one:") => {
"🔂"
};
(":restroom:") => {
"🚻"
};
(":revolving_hearts:") => {
"💞"
};
(":rewind:") => {
"⏪"
};
(":rhino:") => {
"🦏"
};
(":ribbon:") => {
"🎀"
};
(":rice:") => {
"🍚"
};
(":rice_ball:") => {
"🍙"
};
(":rice_cracker:") => {
"🍘"
};
(":rice_scene:") => {
"🎑"
};
(":right_facing_fist:") => {
"🤜"
};
(":right_facing_fist_tone1:") => {
"🤜🏻"
};
(":right_facing_fist_tone2:") => {
"🤜🏼"
};
(":right_facing_fist_tone3:") => {
"🤜🏽"
};
(":right_facing_fist_tone4:") => {
"🤜🏾"
};
(":right_facing_fist_tone5:") => {
"🤜🏿"
};
(":ring:") => {
"💍"
};
(":robot:") => {
"🤖"
};
(":rocket:") => {
"🚀"
};
(":rofl:") => {
"🤣"
};
(":roller_coaster:") => {
"🎢"
};
(":rolling_eyes:") => {
"🙄"
};
(":rooster:") => {
"🐓"
};
(":rose:") => {
"🌹"
};
(":rosette:") => {
"🏵"
};
(":rotating_light:") => {
"🚨"
};
(":round_pushpin:") => {
"📍"
};
(":rugby_football:") => {
"🏉"
};
(":running_shirt_with_sash:") => {
"🎽"
};
(":sa:") => {
"🈂"
};
(":sagittarius:") => {
"♐"
};
(":sailboat:") => {
"⛵"
};
(":sake:") => {
"🍶"
};
(":salad:") => {
"🥗"
};
(":sandal:") => {
"👡"
};
(":sandwich:") => {
"🥪"
};
(":santa:") => {
"🎅"
};
(":santa_tone1:") => {
"🎅🏻"
};
(":santa_tone2:") => {
"🎅🏼"
};
(":santa_tone3:") => {
"🎅🏽"
};
(":santa_tone4:") => {
"🎅🏾"
};
(":santa_tone5:") => {
"🎅🏿"
};
(":satellite:") => {
"📡"
};
(":satellite_orbital:") => {
"🛰"
};
(":sauropod:") => {
"🦕"
};
(":saxophone:") => {
"🎷"
};
(":scales:") => {
"⚖"
};
(":scarf:") => {
"🧣"
};
(":school:") => {
"🏫"
};
(":school_satchel:") => {
"🎒"
};
(":scissors:") => {
"✂"
};
(":scooter:") => {
"🛴"
};
(":scorpion:") => {
"🦂"
};
(":scorpius:") => {
"♏"
};
(":scotland:") => {
"🏴"
};
(":scream:") => {
"😱"
};
(":scream_cat:") => {
"🙀"
};
(":scroll:") => {
"📜"
};
(":seat:") => {
"💺"
};
(":second_place:") => {
"🥈"
};
(":secret:") => {
"㊙"
};
(":see_no_evil:") => {
"🙈"
};
(":seedling:") => {
"🌱"
};
(":selfie:") => {
"🤳"
};
(":selfie_tone1:") => {
"🤳🏻"
};
(":selfie_tone2:") => {
"🤳🏼"
};
(":selfie_tone3:") => {
"🤳🏽"
};
(":selfie_tone4:") => {
"🤳🏾"
};
(":selfie_tone5:") => {
"🤳🏿"
};
(":seven:") => {
"7⃣"
};
(":shallow_pan_of_food:") => {
"🥘"
};
(":shamrock:") => {
"☘"
};
(":shark:") => {
"🦈"
};
(":shaved_ice:") => {
"🍧"
};
(":sheep:") => {
"🐑"
};
(":shell:") => {
"🐚"
};
(":shield:") => {
"🛡"
};
(":shinto_shrine:") => {
"⛩"
};
(":ship:") => {
"🚢"
};
(":shirt:") => {
"👕"
};
(":shopping_bags:") => {
"🛍"
};
(":shopping_cart:") => {
"🛒"
};
(":shower:") => {
"🚿"
};
(":shrimp:") => {
"🦐"
};
(":shushing_face:") => {
"🤫"
};
(":signal_strength:") => {
"📶"
};
(":six:") => {
"6⃣"
};
(":six_pointed_star:") => {
"🔯"
};
(":ski:") => {
"🎿"
};
(":skier:") => {
"⛷"
};
(":skull:") => {
"💀"
};
(":skull_crossbones:") => {
"☠"
};
(":sled:") => {
"🛷"
};
(":sleeping:") => {
"😴"
};
(":sleeping_accommodation:") => {
"🛌"
};
(":sleepy:") => {
"😪"
};
(":slight_frown:") => {
"🙁"
};
(":slight_smile:") => {
"🙂"
};
(":slot_machine:") => {
"🎰"
};
(":small_blue_diamond:") => {
"🔹"
};
(":small_orange_diamond:") => {
"🔸"
};
(":small_red_triangle:") => {
"🔺"
};
(":small_red_triangle_down:") => {
"🔻"
};
(":smile:") => {
"😄"
};
(":smile_cat:") => {
"😸"
};
(":smiley:") => {
"😃"
};
(":smiley_cat:") => {
"😺"
};
(":smiling_imp:") => {
"😈"
};
(":smirk:") => {
"😏"
};
(":smirk_cat:") => {
"😼"
};
(":smoking:") => {
"🚬"
};
(":snail:") => {
"🐌"
};
(":snake:") => {
"🐍"
};
(":sneezing_face:") => {
"🤧"
};
(":snowboarder:") => {
"🏂"
};
(":snowboarder_tone1:") => {
"🏂🏻"
};
(":snowboarder_tone2:") => {
"🏂🏼"
};
(":snowboarder_tone3:") => {
"🏂🏽"
};
(":snowboarder_tone4:") => {
"🏂🏾"
};
(":snowboarder_tone5:") => {
"🏂🏿"
};
(":snowflake:") => {
"❄"
};
(":snowman2:") => {
"☃"
};
(":snowman:") => {
"⛄"
};
(":sob:") => {
"😭"
};
(":soccer:") => {
"⚽"
};
(":socks:") => {
"🧦"
};
(":soon:") => {
"🔜"
};
(":sos:") => {
"🆘"
};
(":sound:") => {
"🔉"
};
(":space_invader:") => {
"👾"
};
(":spades:") => {
"♠"
};
(":spaghetti:") => {
"🍝"
};
(":sparkle:") => {
"❇"
};
(":sparkler:") => {
"🎇"
};
(":sparkles:") => {
"✨"
};
(":sparkling_heart:") => {
"💖"
};
(":speak_no_evil:") => {
"🙊"
};
(":speaker:") => {
"🔈"
};
(":speaking_head:") => {
"🗣"
};
(":speech_balloon:") => {
"💬"
};
(":speech_left:") => {
"🗨"
};
(":speedboat:") => {
"🚤"
};
(":spider:") => {
"🕷"
};
(":spider_web:") => {
"🕸"
};
(":spoon:") => {
"🥄"
};
(":squid:") => {
"🦑"
};
(":stadium:") => {
"🏟"
};
(":star2:") => {
"🌟"
};
(":star:") => {
"⭐"
};
(":star_and_crescent:") => {
"☪"
};
(":star_of_david:") => {
"✡"
};
(":star_struck:") => {
"🤩"
};
(":stars:") => {
"🌠"
};
(":station:") => {
"🚉"
};
(":statue_of_liberty:") => {
"🗽"
};
(":steam_locomotive:") => {
"🚂"
};
(":stew:") => {
"🍲"
};
(":stop_button:") => {
"⏹"
};
(":stopwatch:") => {
"⏱"
};
(":straight_ruler:") => {
"📏"
};
(":strawberry:") => {
"🍓"
};
(":stuck_out_tongue:") => {
"😛"
};
(":stuck_out_tongue_closed_eyes:") => {
"😝"
};
(":stuck_out_tongue_winking_eye:") => {
"😜"
};
(":stuffed_flatbread:") => {
"🥙"
};
(":sun_with_face:") => {
"🌞"
};
(":sunflower:") => {
"🌻"
};
(":sunglasses:") => {
"😎"
};
(":sunny:") => {
"☀"
};
(":sunrise:") => {
"🌅"
};
(":sunrise_over_mountains:") => {
"🌄"
};
(":sushi:") => {
"🍣"
};
(":suspension_railway:") => {
"🚟"
};
(":sweat:") => {
"😓"
};
(":sweat_drops:") => {
"💦"
};
(":sweat_smile:") => {
"😅"
};
(":sweet_potato:") => {
"🍠"
};
(":symbols:") => {
"🔣"
};
(":synagogue:") => {
"🕍"
};
(":syringe:") => {
"💉"
};
(":t_rex:") => {
"🦖"
};
(":taco:") => {
"🌮"
};
(":tada:") => {
"🎉"
};
(":takeout_box:") => {
"🥡"
};
(":tanabata_tree:") => {
"🎋"
};
(":tangerine:") => {
"🍊"
};
(":taurus:") => {
"♉"
};
(":taxi:") => {
"🚕"
};
(":tea:") => {
"🍵"
};
(":telephone:") => {
"☎"
};
(":telephone_receiver:") => {
"📞"
};
(":telescope:") => {
"🔭"
};
(":tennis:") => {
"🎾"
};
(":tent:") => {
"⛺"
};
(":thermometer:") => {
"🌡"
};
(":thermometer_face:") => {
"🤒"
};
(":thinking:") => {
"🤔"
};
(":third_place:") => {
"🥉"
};
(":thought_balloon:") => {
"💭"
};
(":three:") => {
"3⃣"
};
(":thumbsdown:") => {
"👎"
};
(":thumbsdown_tone1:") => {
"👎🏻"
};
(":thumbsdown_tone2:") => {
"👎🏼"
};
(":thumbsdown_tone3:") => {
"👎🏽"
};
(":thumbsdown_tone4:") => {
"👎🏾"
};
(":thumbsdown_tone5:") => {
"👎🏿"
};
(":thumbsup:") => {
"👍"
};
(":thumbsup_tone1:") => {
"👍🏻"
};
(":thumbsup_tone2:") => {
"👍🏼"
};
(":thumbsup_tone3:") => {
"👍🏽"
};
(":thumbsup_tone4:") => {
"👍🏾"
};
(":thumbsup_tone5:") => {
"👍🏿"
};
(":thunder_cloud_rain:") => {
"⛈"
};
(":ticket:") => {
"🎫"
};
(":tickets:") => {
"🎟"
};
(":tiger2:") => {
"🐅"
};
(":tiger:") => {
"🐯"
};
(":timer:") => {
"⏲"
};
(":tired_face:") => {
"😫"
};
(":tm:") => {
"™"
};
(":toilet:") => {
"🚽"
};
(":tokyo_tower:") => {
"🗼"
};
(":tomato:") => {
"🍅"
};
(":tone1:") => {
"🏻"
};
(":tone2:") => {
"🏼"
};
(":tone3:") => {
"🏽"
};
(":tone4:") => {
"🏾"
};
(":tone5:") => {
"🏿"
};
(":tongue:") => {
"👅"
};
(":tools:") => {
"🛠"
};
(":top:") => {
"🔝"
};
(":tophat:") => {
"🎩"
};
(":track_next:") => {
"⏭"
};
(":track_previous:") => {
"⏮"
};
(":trackball:") => {
"🖲"
};
(":tractor:") => {
"🚜"
};
(":traffic_light:") => {
"🚥"
};
(":train2:") => {
"🚆"
};
(":train:") => {
"🚋"
};
(":tram:") => {
"🚊"
};
(":triangular_flag_on_post:") => {
"🚩"
};
(":triangular_ruler:") => {
"📐"
};
(":trident:") => {
"🔱"
};
(":triumph:") => {
"😤"
};
(":trolleybus:") => {
"🚎"
};
(":trophy:") => {
"🏆"
};
(":tropical_drink:") => {
"🍹"
};
(":tropical_fish:") => {
"🐠"
};
(":truck:") => {
"🚚"
};
(":trumpet:") => {
"🎺"
};
(":tulip:") => {
"🌷"
};
(":tumbler_glass:") => {
"🥃"
};
(":turkey:") => {
"🦃"
};
(":turtle:") => {
"🐢"
};
(":tv:") => {
"📺"
};
(":twisted_rightwards_arrows:") => {
"🔀"
};
(":two:") => {
"2⃣"
};
(":two_hearts:") => {
"💕"
};
(":two_men_holding_hands:") => {
"👬"
};
(":two_women_holding_hands:") => {
"👭"
};
(":u5272:") => {
"🈹"
};
(":u5408:") => {
"🈴"
};
(":u55b6:") => {
"🈺"
};
(":u6307:") => {
"🈯"
};
(":u6708:") => {
"🈷"
};
(":u6709:") => {
"🈶"
};
(":u6e80:") => {
"🈵"
};
(":u7121:") => {
"🈚"
};
(":u7533:") => {
"🈸"
};
(":u7981:") => {
"🈲"
};
(":u7a7a:") => {
"🈳"
};
(":umbrella2:") => {
"☂"
};
(":umbrella:") => {
"☔"
};
(":unamused:") => {
"😒"
};
(":underage:") => {
"🔞"
};
(":unicorn:") => {
"🦄"
};
(":united_nations:") => {
"🇺🇳"
};
(":unlock:") => {
"🔓"
};
(":up:") => {
"🆙"
};
(":upside_down:") => {
"🙃"
};
(":urn:") => {
"⚱"
};
(":v:") => {
"✌"
};
(":v_tone1:") => {
"✌🏻"
};
(":v_tone2:") => {
"✌🏼"
};
(":v_tone3:") => {
"✌🏽"
};
(":v_tone4:") => {
"✌🏾"
};
(":v_tone5:") => {
"✌🏿"
};
(":vampire:") => {
"🧛"
};
(":vampire_tone1:") => {
"🧛🏻"
};
(":vampire_tone2:") => {
"🧛🏼"
};
(":vampire_tone3:") => {
"🧛🏽"
};
(":vampire_tone4:") => {
"🧛🏾"
};
(":vampire_tone5:") => {
"🧛🏿"
};
(":vertical_traffic_light:") => {
"🚦"
};
(":vhs:") => {
"📼"
};
(":vibration_mode:") => {
"📳"
};
(":video_camera:") => {
"📹"
};
(":video_game:") => {
"🎮"
};
(":violin:") => {
"🎻"
};
(":virgo:") => {
"♍"
};
(":volcano:") => {
"🌋"
};
(":volleyball:") => {
"🏐"
};
(":vs:") => {
"🆚"
};
(":vulcan:") => {
"🖖"
};
(":vulcan_tone1:") => {
"🖖🏻"
};
(":vulcan_tone2:") => {
"🖖🏼"
};
(":vulcan_tone3:") => {
"🖖🏽"
};
(":vulcan_tone4:") => {
"🖖🏾"
};
(":vulcan_tone5:") => {
"🖖🏿"
};
(":wales:") => {
"🏴"
};
(":waning_crescent_moon:") => {
"🌘"
};
(":waning_gibbous_moon:") => {
"🌖"
};
(":warning:") => {
"⚠"
};
(":wastebasket:") => {
"🗑"
};
(":watch:") => {
"⌚"
};
(":water_buffalo:") => {
"🐃"
};
(":watermelon:") => {
"🍉"
};
(":wave:") => {
"👋"
};
(":wave_tone1:") => {
"👋🏻"
};
(":wave_tone2:") => {
"👋🏼"
};
(":wave_tone3:") => {
"👋🏽"
};
(":wave_tone4:") => {
"👋🏾"
};
(":wave_tone5:") => {
"👋🏿"
};
(":wavy_dash:") => {
"〰"
};
(":waxing_crescent_moon:") => {
"🌒"
};
(":waxing_gibbous_moon:") => {
"🌔"
};
(":wc:") => {
"🚾"
};
(":weary:") => {
"😩"
};
(":wedding:") => {
"💒"
};
(":whale2:") => {
"🐋"
};
(":whale:") => {
"🐳"
};
(":wheel_of_dharma:") => {
"☸"
};
(":wheelchair:") => {
"♿"
};
(":white_check_mark:") => {
"✅"
};
(":white_circle:") => {
"⚪"
};
(":white_flower:") => {
"💮"
};
(":white_large_square:") => {
"⬜"
};
(":white_medium_small_square:") => {
"◽"
};
(":white_medium_square:") => {
"◻"
};
(":white_small_square:") => {
"▫"
};
(":white_square_button:") => {
"🔳"
};
(":white_sun_cloud:") => {
"🌥"
};
(":white_sun_rain_cloud:") => {
"🌦"
};
(":white_sun_small_cloud:") => {
"🌤"
};
(":wilted_rose:") => {
"🥀"
};
(":wind_blowing_face:") => {
"🌬"
};
(":wind_chime:") => {
"🎐"
};
(":wine_glass:") => {
"🍷"
};
(":wink:") => {
"😉"
};
(":wolf:") => {
"🐺"
};
(":woman:") => {
"👩"
};
(":woman_artist:") => {
"👩🎨"
};
(":woman_artist_tone1:") => {
"👩🏻🎨"
};
(":woman_artist_tone2:") => {
"👩🏼🎨"
};
(":woman_artist_tone3:") => {
"👩🏽🎨"
};
(":woman_artist_tone4:") => {
"👩🏾🎨"
};
(":woman_artist_tone5:") => {
"👩🏿🎨"
};
(":woman_astronaut:") => {
"👩🚀"
};
(":woman_astronaut_tone1:") => {
"👩🏻🚀"
};
(":woman_astronaut_tone2:") => {
"👩🏼🚀"
};
(":woman_astronaut_tone3:") => {
"👩🏽🚀"
};
(":woman_astronaut_tone4:") => {
"👩🏾🚀"
};
(":woman_astronaut_tone5:") => {
"👩🏿🚀"
};
(":woman_biking:") => {
"🚴♀"
};
(":woman_biking_tone1:") => {
"🚴🏻♀"
};
(":woman_biking_tone2:") => {
"🚴🏼♀"
};
(":woman_biking_tone3:") => {
"🚴🏽♀"
};
(":woman_biking_tone4:") => {
"🚴🏾♀"
};
(":woman_biking_tone5:") => {
"🚴🏿♀"
};
(":woman_bouncing_ball:") => {
"⛹♀"
};
(":woman_bouncing_ball_tone1:") => {
"⛹🏻♀"
};
(":woman_bouncing_ball_tone2:") => {
"⛹🏼♀"
};
(":woman_bouncing_ball_tone3:") => {
"⛹🏽♀"
};
(":woman_bouncing_ball_tone4:") => {
"⛹🏾♀"
};
(":woman_bouncing_ball_tone5:") => {
"⛹🏿♀"
};
(":woman_bowing:") => {
"🙇♀"
};
(":woman_bowing_tone1:") => {
"🙇🏻♀"
};
(":woman_bowing_tone2:") => {
"🙇🏼♀"
};
(":woman_bowing_tone3:") => {
"🙇🏽♀"
};
(":woman_bowing_tone4:") => {
"🙇🏾♀"
};
(":woman_bowing_tone5:") => {
"🙇🏿♀"
};
(":woman_cartwheeling:") => {
"🤸♀"
};
(":woman_cartwheeling_tone1:") => {
"🤸🏻♀"
};
(":woman_cartwheeling_tone2:") => {
"🤸🏼♀"
};
(":woman_cartwheeling_tone3:") => {
"🤸🏽♀"
};
(":woman_cartwheeling_tone4:") => {
"🤸🏾♀"
};
(":woman_cartwheeling_tone5:") => {
"🤸🏿♀"
};
(":woman_climbing:") => {
"🧗♀"
};
(":woman_climbing_tone1:") => {
"🧗🏻♀"
};
(":woman_climbing_tone2:") => {
"🧗🏼♀"
};
(":woman_climbing_tone3:") => {
"🧗🏽♀"
};
(":woman_climbing_tone4:") => {
"🧗🏾♀"
};
(":woman_climbing_tone5:") => {
"🧗🏿♀"
};
(":woman_construction_worker:") => {
"👷♀"
};
(":woman_construction_worker_tone1:") => {
"👷🏻♀"
};
(":woman_construction_worker_tone2:") => {
"👷🏼♀"
};
(":woman_construction_worker_tone3:") => {
"👷🏽♀"
};
(":woman_construction_worker_tone4:") => {
"👷🏾♀"
};
(":woman_construction_worker_tone5:") => {
"👷🏿♀"
};
(":woman_cook:") => {
"👩🍳"
};
(":woman_cook_tone1:") => {
"👩🏻🍳"
};
(":woman_cook_tone2:") => {
"👩🏼🍳"
};
(":woman_cook_tone3:") => {
"👩🏽🍳"
};
(":woman_cook_tone4:") => {
"👩🏾🍳"
};
(":woman_cook_tone5:") => {
"👩🏿🍳"
};
(":woman_detective:") => {
"🕵♀"
};
(":woman_detective_tone1:") => {
"🕵🏻♀"
};
(":woman_detective_tone2:") => {
"🕵🏼♀"
};
(":woman_detective_tone3:") => {
"🕵🏽♀"
};
(":woman_detective_tone4:") => {
"🕵🏾♀"
};
(":woman_detective_tone5:") => {
"🕵🏿♀"
};
(":woman_elf:") => {
"🧝♀"
};
(":woman_elf_tone1:") => {
"🧝🏻♀"
};
(":woman_elf_tone2:") => {
"🧝🏼♀"
};
(":woman_elf_tone3:") => {
"🧝🏽♀"
};
(":woman_elf_tone4:") => {
"🧝🏾♀"
};
(":woman_elf_tone5:") => {
"🧝🏿♀"
};
(":woman_facepalming:") => {
"🤦♀"
};
(":woman_facepalming_tone1:") => {
"🤦🏻♀"
};
(":woman_facepalming_tone2:") => {
"🤦🏼♀"
};
(":woman_facepalming_tone3:") => {
"🤦🏽♀"
};
(":woman_facepalming_tone4:") => {
"🤦🏾♀"
};
(":woman_facepalming_tone5:") => {
"🤦🏿♀"
};
(":woman_factory_worker:") => {
"👩🏭"
};
(":woman_factory_worker_tone1:") => {
"👩🏻🏭"
};
(":woman_factory_worker_tone2:") => {
"👩🏼🏭"
};
(":woman_factory_worker_tone3:") => {
"👩🏽🏭"
};
(":woman_factory_worker_tone4:") => {
"👩🏾🏭"
};
(":woman_factory_worker_tone5:") => {
"👩🏿🏭"
};
(":woman_fairy:") => {
"🧚♀"
};
(":woman_fairy_tone1:") => {
"🧚🏻♀"
};
(":woman_fairy_tone2:") => {
"🧚🏼♀"
};
(":woman_fairy_tone3:") => {
"🧚🏽♀"
};
(":woman_fairy_tone4:") => {
"🧚🏾♀"
};
(":woman_fairy_tone5:") => {
"🧚🏿♀"
};
(":woman_farmer:") => {
"👩🌾"
};
(":woman_farmer_tone1:") => {
"👩🏻🌾"
};
(":woman_farmer_tone2:") => {
"👩🏼🌾"
};
(":woman_farmer_tone3:") => {
"👩🏽🌾"
};
(":woman_farmer_tone4:") => {
"👩🏾🌾"
};
(":woman_farmer_tone5:") => {
"👩🏿🌾"
};
(":woman_firefighter:") => {
"👩🚒"
};
(":woman_firefighter_tone1:") => {
"👩🏻🚒"
};
(":woman_firefighter_tone2:") => {
"👩🏼🚒"
};
(":woman_firefighter_tone3:") => {
"👩🏽🚒"
};
(":woman_firefighter_tone4:") => {
"👩🏾🚒"
};
(":woman_firefighter_tone5:") => {
"👩🏿🚒"
};
(":woman_frowning:") => {
"🙍♀"
};
(":woman_frowning_tone1:") => {
"🙍🏻♀"
};
(":woman_frowning_tone2:") => {
"🙍🏼♀"
};
(":woman_frowning_tone3:") => {
"🙍🏽♀"
};
(":woman_frowning_tone4:") => {
"🙍🏾♀"
};
(":woman_frowning_tone5:") => {
"🙍🏿♀"
};
(":woman_genie:") => {
"🧞♀"
};
(":woman_gesturing_no:") => {
"🙅♀"
};
(":woman_gesturing_no_tone1:") => {
"🙅🏻♀"
};
(":woman_gesturing_no_tone2:") => {
"🙅🏼♀"
};
(":woman_gesturing_no_tone3:") => {
"🙅🏽♀"
};
(":woman_gesturing_no_tone4:") => {
"🙅🏾♀"
};
(":woman_gesturing_no_tone5:") => {
"🙅🏿♀"
};
(":woman_gesturing_ok:") => {
"🙆♀"
};
(":woman_gesturing_ok_tone1:") => {
"🙆🏻♀"
};
(":woman_gesturing_ok_tone2:") => {
"🙆🏼♀"
};
(":woman_gesturing_ok_tone3:") => {
"🙆🏽♀"
};
(":woman_gesturing_ok_tone4:") => {
"🙆🏾♀"
};
(":woman_gesturing_ok_tone5:") => {
"🙆🏿♀"
};
(":woman_getting_face_massage:") => {
"💆♀"
};
(":woman_getting_face_massage_tone1:") => {
"💆🏻♀"
};
(":woman_getting_face_massage_tone2:") => {
"💆🏼♀"
};
(":woman_getting_face_massage_tone3:") => {
"💆🏽♀"
};
(":woman_getting_face_massage_tone4:") => {
"💆🏾♀"
};
(":woman_getting_face_massage_tone5:") => {
"💆🏿♀"
};
(":woman_getting_haircut:") => {
"💇♀"
};
(":woman_getting_haircut_tone1:") => {
"💇🏻♀"
};
(":woman_getting_haircut_tone2:") => {
"💇🏼♀"
};
(":woman_getting_haircut_tone3:") => {
"💇🏽♀"
};
(":woman_getting_haircut_tone4:") => {
"💇🏾♀"
};
(":woman_getting_haircut_tone5:") => {
"💇🏿♀"
};
(":woman_golfing:") => {
"🏌♀"
};
(":woman_golfing_tone1:") => {
"🏌🏻♀"
};
(":woman_golfing_tone2:") => {
"🏌🏼♀"
};
(":woman_golfing_tone3:") => {
"🏌🏽♀"
};
(":woman_golfing_tone4:") => {
"🏌🏾♀"
};
(":woman_golfing_tone5:") => {
"🏌🏿♀"
};
(":woman_guard:") => {
"💂♀"
};
(":woman_guard_tone1:") => {
"💂🏻♀"
};
(":woman_guard_tone2:") => {
"💂🏼♀"
};
(":woman_guard_tone3:") => {
"💂🏽♀"
};
(":woman_guard_tone4:") => {
"💂🏾♀"
};
(":woman_guard_tone5:") => {
"💂🏿♀"
};
(":woman_health_worker:") => {
"👩⚕"
};
(":woman_health_worker_tone1:") => {
"👩🏻⚕"
};
(":woman_health_worker_tone2:") => {
"👩🏼⚕"
};
(":woman_health_worker_tone3:") => {
"👩🏽⚕"
};
(":woman_health_worker_tone4:") => {
"👩🏾⚕"
};
(":woman_health_worker_tone5:") => {
"👩🏿⚕"
};
(":woman_in_lotus_position:") => {
"🧘♀"
};
(":woman_in_lotus_position_tone1:") => {
"🧘🏻♀"
};
(":woman_in_lotus_position_tone2:") => {
"🧘🏼♀"
};
(":woman_in_lotus_position_tone3:") => {
"🧘🏽♀"
};
(":woman_in_lotus_position_tone4:") => {
"🧘🏾♀"
};
(":woman_in_lotus_position_tone5:") => {
"🧘🏿♀"
};
(":woman_in_steamy_room:") => {
"🧖♀"
};
(":woman_in_steamy_room_tone1:") => {
"🧖🏻♀"
};
(":woman_in_steamy_room_tone2:") => {
"🧖🏼♀"
};
(":woman_in_steamy_room_tone3:") => {
"🧖🏽♀"
};
(":woman_in_steamy_room_tone4:") => {
"🧖🏾♀"
};
(":woman_in_steamy_room_tone5:") => {
"🧖🏿♀"
};
(":woman_judge:") => {
"👩⚖"
};
(":woman_judge_tone1:") => {
"👩🏻⚖"
};
(":woman_judge_tone2:") => {
"👩🏼⚖"
};
(":woman_judge_tone3:") => {
"👩🏽⚖"
};
(":woman_judge_tone4:") => {
"👩🏾⚖"
};
(":woman_judge_tone5:") => {
"👩🏿⚖"
};
(":woman_juggling:") => {
"🤹♀"
};
(":woman_juggling_tone1:") => {
"🤹🏻♀"
};
(":woman_juggling_tone2:") => {
"🤹🏼♀"
};
(":woman_juggling_tone3:") => {
"🤹🏽♀"
};
(":woman_juggling_tone4:") => {
"🤹🏾♀"
};
(":woman_juggling_tone5:") => {
"🤹🏿♀"
};
(":woman_lifting_weights:") => {
"🏋♀"
};
(":woman_lifting_weights_tone1:") => {
"🏋🏻♀"
};
(":woman_lifting_weights_tone2:") => {
"🏋🏼♀"
};
(":woman_lifting_weights_tone3:") => {
"🏋🏽♀"
};
(":woman_lifting_weights_tone4:") => {
"🏋🏾♀"
};
(":woman_lifting_weights_tone5:") => {
"🏋🏿♀"
};
(":woman_mage:") => {
"🧙♀"
};
(":woman_mage_tone1:") => {
"🧙🏻♀"
};
(":woman_mage_tone2:") => {
"🧙🏼♀"
};
(":woman_mage_tone3:") => {
"🧙🏽♀"
};
(":woman_mage_tone4:") => {
"🧙🏾♀"
};
(":woman_mage_tone5:") => {
"🧙🏿♀"
};
(":woman_mechanic:") => {
"👩🔧"
};
(":woman_mechanic_tone1:") => {
"👩🏻🔧"
};
(":woman_mechanic_tone2:") => {
"👩🏼🔧"
};
(":woman_mechanic_tone3:") => {
"👩🏽🔧"
};
(":woman_mechanic_tone4:") => {
"👩🏾🔧"
};
(":woman_mechanic_tone5:") => {
"👩🏿🔧"
};
(":woman_mountain_biking:") => {
"🚵♀"
};
(":woman_mountain_biking_tone1:") => {
"🚵🏻♀"
};
(":woman_mountain_biking_tone2:") => {
"🚵🏼♀"
};
(":woman_mountain_biking_tone3:") => {
"🚵🏽♀"
};
(":woman_mountain_biking_tone4:") => {
"🚵🏾♀"
};
(":woman_mountain_biking_tone5:") => {
"🚵🏿♀"
};
(":woman_office_worker:") => {
"👩💼"
};
(":woman_office_worker_tone1:") => {
"👩🏻💼"
};
(":woman_office_worker_tone2:") => {
"👩🏼💼"
};
(":woman_office_worker_tone3:") => {
"👩🏽💼"
};
(":woman_office_worker_tone4:") => {
"👩🏾💼"
};
(":woman_office_worker_tone5:") => {
"👩🏿💼"
};
(":woman_pilot:") => {
"👩✈"
};
(":woman_pilot_tone1:") => {
"👩🏻✈"
};
(":woman_pilot_tone2:") => {
"👩🏼✈"
};
(":woman_pilot_tone3:") => {
"👩🏽✈"
};
(":woman_pilot_tone4:") => {
"👩🏾✈"
};
(":woman_pilot_tone5:") => {
"👩🏿✈"
};
(":woman_playing_handball:") => {
"🤾♀"
};
(":woman_playing_handball_tone1:") => {
"🤾🏻♀"
};
(":woman_playing_handball_tone2:") => {
"🤾🏼♀"
};
(":woman_playing_handball_tone3:") => {
"🤾🏽♀"
};
(":woman_playing_handball_tone4:") => {
"🤾🏾♀"
};
(":woman_playing_handball_tone5:") => {
"🤾🏿♀"
};
(":woman_playing_water_polo:") => {
"🤽♀"
};
(":woman_playing_water_polo_tone1:") => {
"🤽🏻♀"
};
(":woman_playing_water_polo_tone2:") => {
"🤽🏼♀"
};
(":woman_playing_water_polo_tone3:") => {
"🤽🏽♀"
};
(":woman_playing_water_polo_tone4:") => {
"🤽🏾♀"
};
(":woman_playing_water_polo_tone5:") => {
"🤽🏿♀"
};
(":woman_police_officer:") => {
"👮♀"
};
(":woman_police_officer_tone1:") => {
"👮🏻♀"
};
(":woman_police_officer_tone2:") => {
"👮🏼♀"
};
(":woman_police_officer_tone3:") => {
"👮🏽♀"
};
(":woman_police_officer_tone4:") => {
"👮🏾♀"
};
(":woman_police_officer_tone5:") => {
"👮🏿♀"
};
(":woman_pouting:") => {
"🙎♀"
};
(":woman_pouting_tone1:") => {
"🙎🏻♀"
};
(":woman_pouting_tone2:") => {
"🙎🏼♀"
};
(":woman_pouting_tone3:") => {
"🙎🏽♀"
};
(":woman_pouting_tone4:") => {
"🙎🏾♀"
};
(":woman_pouting_tone5:") => {
"🙎🏿♀"
};
(":woman_raising_hand:") => {
"🙋♀"
};
(":woman_raising_hand_tone1:") => {
"🙋🏻♀"
};
(":woman_raising_hand_tone2:") => {
"🙋🏼♀"
};
(":woman_raising_hand_tone3:") => {
"🙋🏽♀"
};
(":woman_raising_hand_tone4:") => {
"🙋🏾♀"
};
(":woman_raising_hand_tone5:") => {
"🙋🏿♀"
};
(":woman_rowing_boat:") => {
"🚣♀"
};
(":woman_rowing_boat_tone1:") => {
"🚣🏻♀"
};
(":woman_rowing_boat_tone2:") => {
"🚣🏼♀"
};
(":woman_rowing_boat_tone3:") => {
"🚣🏽♀"
};
(":woman_rowing_boat_tone4:") => {
"🚣🏾♀"
};
(":woman_rowing_boat_tone5:") => {
"🚣🏿♀"
};
(":woman_running:") => {
"🏃♀"
};
(":woman_running_tone1:") => {
"🏃🏻♀"
};
(":woman_running_tone2:") => {
"🏃🏼♀"
};
(":woman_running_tone3:") => {
"🏃🏽♀"
};
(":woman_running_tone4:") => {
"🏃🏾♀"
};
(":woman_running_tone5:") => {
"🏃🏿♀"
};
(":woman_scientist:") => {
"👩🔬"
};
(":woman_scientist_tone1:") => {
"👩🏻🔬"
};
(":woman_scientist_tone2:") => {
"👩🏼🔬"
};
(":woman_scientist_tone3:") => {
"👩🏽🔬"
};
(":woman_scientist_tone4:") => {
"👩🏾🔬"
};
(":woman_scientist_tone5:") => {
"👩🏿🔬"
};
(":woman_shrugging:") => {
"🤷♀"
};
(":woman_shrugging_tone1:") => {
"🤷🏻♀"
};
(":woman_shrugging_tone2:") => {
"🤷🏼♀"
};
(":woman_shrugging_tone3:") => {
"����🏽♀"
};
(":woman_shrugging_tone4:") => {
"🤷🏾♀"
};
(":woman_shrugging_tone5:") => {
"🤷🏿♀"
};
(":woman_singer:") => {
"👩🎤"
};
(":woman_singer_tone1:") => {
"👩🏻🎤"
};
(":woman_singer_tone2:") => {
"👩🏼🎤"
};
(":woman_singer_tone3:") => {
"👩🏽🎤"
};
(":woman_singer_tone4:") => {
"👩🏾🎤"
};
(":woman_singer_tone5:") => {
"👩🏿🎤"
};
(":woman_student:") => {
"👩🎓"
};
(":woman_student_tone1:") => {
"👩🏻🎓"
};
(":woman_student_tone2:") => {
"👩🏼🎓"
};
(":woman_student_tone3:") => {
"👩🏽🎓"
};
(":woman_student_tone4:") => {
"👩🏾🎓"
};
(":woman_student_tone5:") => {
"👩🏿🎓"
};
(":woman_surfing:") => {
"🏄♀"
};
(":woman_surfing_tone1:") => {
"🏄🏻♀"
};
(":woman_surfing_tone2:") => {
"🏄🏼♀"
};
(":woman_surfing_tone3:") => {
"🏄🏽♀"
};
(":woman_surfing_tone4:") => {
"🏄🏾♀"
};
(":woman_surfing_tone5:") => {
"🏄🏿♀"
};
(":woman_swimming:") => {
"🏊♀"
};
(":woman_swimming_tone1:") => {
"🏊🏻♀"
};
(":woman_swimming_tone2:") => {
"🏊🏼♀"
};
(":woman_swimming_tone3:") => {
"🏊🏽♀"
};
(":woman_swimming_tone4:") => {
"🏊🏾♀"
};
(":woman_swimming_tone5:") => {
"🏊🏿♀"
};
(":woman_teacher:") => {
"👩🏫"
};
(":woman_teacher_tone1:") => {
"👩🏻🏫"
};
(":woman_teacher_tone2:") => {
"👩🏼🏫"
};
(":woman_teacher_tone3:") => {
"👩🏽🏫"
};
(":woman_teacher_tone4:") => {
"👩🏾🏫"
};
(":woman_teacher_tone5:") => {
"👩🏿🏫"
};
(":woman_technologist:") => {
"👩💻"
};
(":woman_technologist_tone1:") => {
"👩🏻💻"
};
(":woman_technologist_tone2:") => {
"👩🏼💻"
};
(":woman_technologist_tone3:") => {
"👩🏽💻"
};
(":woman_technologist_tone4:") => {
"👩🏾💻"
};
(":woman_technologist_tone5:") => {
"👩🏿💻"
};
(":woman_tipping_hand:") => {
"💁♀"
};
(":woman_tipping_hand_tone1:") => {
"💁🏻♀"
};
(":woman_tipping_hand_tone2:") => {
"💁🏼♀"
};
(":woman_tipping_hand_tone3:") => {
"💁🏽♀"
};
(":woman_tipping_hand_tone4:") => {
"💁🏾♀"
};
(":woman_tipping_hand_tone5:") => {
"💁🏿♀"
};
(":woman_tone1:") => {
"👩🏻"
};
(":woman_tone2:") => {
"👩🏼"
};
(":woman_tone3:") => {
"👩🏽"
};
(":woman_tone4:") => {
"👩🏾"
};
(":woman_tone5:") => {
"👩🏿"
};
(":woman_vampire:") => {
"🧛♀"
};
(":woman_vampire_tone1:") => {
"🧛🏻♀"
};
(":woman_vampire_tone2:") => {
"🧛🏼♀"
};
(":woman_vampire_tone3:") => {
"🧛🏽♀"
};
(":woman_vampire_tone4:") => {
"🧛🏾♀"
};
(":woman_vampire_tone5:") => {
"🧛🏿♀"
};
(":woman_walking:") => {
"🚶♀"
};
(":woman_walking_tone1:") => {
"🚶🏻♀"
};
(":woman_walking_tone2:") => {
"🚶🏼♀"
};
(":woman_walking_tone3:") => {
"🚶🏽♀"
};
(":woman_walking_tone4:") => {
"🚶🏾♀"
};
(":woman_walking_tone5:") => {
"🚶🏿♀"
};
(":woman_wearing_turban:") => {
"👳♀"
};
(":woman_wearing_turban_tone1:") => {
"👳🏻♀"
};
(":woman_wearing_turban_tone2:") => {
"👳🏼♀"
};
(":woman_wearing_turban_tone3:") => {
"👳🏽♀"
};
(":woman_wearing_turban_tone4:") => {
"👳🏾♀"
};
(":woman_wearing_turban_tone5:") => {
"👳🏿♀"
};
(":woman_with_headscarf:") => {
"🧕"
};
(":woman_with_headscarf_tone1:") => {
"🧕🏻"
};
(":woman_with_headscarf_tone2:") => {
"🧕🏼"
};
(":woman_with_headscarf_tone3:") => {
"🧕🏽"
};
(":woman_with_headscarf_tone4:") => {
"🧕🏾"
};
(":woman_with_headscarf_tone5:") => {
"🧕🏿"
};
(":woman_zombie:") => {
"🧟♀"
};
(":womans_clothes:") => {
"👚"
};
(":womans_hat:") => {
"👒"
};
(":women_with_bunny_ears_partying:") => {
"👯♀"
};
(":women_wrestling:") => {
"🤼♀"
};
(":womens:") => {
"🚺"
};
(":worried:") => {
"😟"
};
(":wrench:") => {
"🔧"
};
(":writing_hand:") => {
"✍"
};
(":writing_hand_tone1:") => {
"✍🏻"
};
(":writing_hand_tone2:") => {
"✍🏼"
};
(":writing_hand_tone3:") => {
"✍🏽"
};
(":writing_hand_tone4:") => {
"✍🏾"
};
(":writing_hand_tone5:") => {
"✍🏿"
};
(":x:") => {
"❌"
};
(":yellow_heart:") => {
"💛"
};
(":yen:") => {
"💴"
};
(":yin_yang:") => {
"☯"
};
(":yum:") => {
"😋"
};
(":zap:") => {
"⚡"
};
(":zebra:") => {
"🦓"
};
(":zero:") => {
"0⃣"
};
(":zipper_mouth:") => {
"🤐"
};
(":zombie:") => {
"🧟"
};
(":zzz:") => {
"💤"
};
}
|
//! An example hello world contract also used in unit tests.
#![feature(wasm_abi)]
extern crate alloc;
use oasis_contract_sdk::{
self as sdk,
env::{Crypto, Env},
types::{
env::{AccountsQuery, AccountsResponse, QueryRequest, QueryResponse},
message::{CallResult, Message, NotifyReply, Reply},
modules::contracts::InstantiateResult,
token, CodeId, InstanceId,
},
};
use oasis_contract_sdk_oas20_types::{
ReceiverRequest, Request as Oas20Request, TokenInstantiation,
};
use oasis_contract_sdk_storage::cell::Cell;
/// All possible errors that can be returned by the contract.
///
/// Each error is a triplet of (module, code, message) which allows it to be both easily
/// human readable and also identifyable programmatically.
#[derive(Debug, thiserror::Error, sdk::Error)]
pub enum Error {
#[error("bad request")]
#[sdk_error(code = 1)]
BadRequest,
#[error("query failed")]
#[sdk_error(code = 2)]
QueryFailed,
#[error("subcall failed")]
#[sdk_error(code = 3)]
SubcallFailed,
#[error("upgrade not allowed (pre)")]
#[sdk_error(code = 4)]
UpgradeNotAllowedPre,
#[error("upgrade not allowed (post)")]
#[sdk_error(code = 5)]
UpgradeNotAllowedPost,
}
/// All possible events that can be returned by the contract.
#[derive(Debug, cbor::Encode, sdk::Event)]
#[cbor(untagged)]
pub enum Event {
#[sdk_event(code = 1)]
Hello(String),
}
/// All possible requests that the contract can handle.
///
/// This includes both calls and queries.
#[derive(Clone, Debug, cbor::Encode, cbor::Decode)]
pub enum Request {
#[cbor(rename = "instantiate")]
Instantiate { initial_counter: u64 },
#[cbor(rename = "say_hello")]
SayHello { who: String },
#[cbor(rename = "call_self")]
CallSelf,
#[cbor(rename = "increment_counter")]
IncrementCounter,
#[cbor(rename = "instantiate_oas20")]
InstantiateOas20 {
code_id: CodeId,
token_instantiation: TokenInstantiation,
},
#[cbor(rename = "ecdsa_recover")]
ECDSARecover { input: Vec<u8> },
#[cbor(rename = "query_address")]
QueryAddress,
#[cbor(rename = "query_block_info")]
QueryBlockInfo,
#[cbor(rename = "query_accounts")]
QueryAccounts,
#[cbor(rename = "upgrade_proceed")]
UpgradeProceed,
#[cbor(rename = "upgrade_fail_pre")]
UpgradeFailPre,
#[cbor(rename = "upgrade_fail_post")]
UpgradeFailPost,
#[cbor(embed)]
Oas20(ReceiverRequest),
}
/// All possible responses that the contract can return.
///
/// This includes both calls and queries.
#[derive(Clone, Debug, PartialEq, cbor::Encode, cbor::Decode)]
pub enum Response {
#[cbor(rename = "hello")]
Hello { greeting: String },
#[cbor(rename = "instantiate_oas20")]
InstantiateOas20 {
instance_id: InstanceId,
data: String,
},
#[cbor(rename = "ecdsa_recover")]
ECDSARecover { output: [u8; 65] },
#[cbor(rename = "empty")]
Empty,
}
/// The contract type.
pub struct HelloWorld;
/// Storage cell for the counter.
const COUNTER: Cell<u64> = Cell::new(b"counter");
impl HelloWorld {
/// Increment the counter and return the previous value.
fn increment_counter<C: sdk::Context>(ctx: &mut C, inc: u64) -> u64 {
let counter = COUNTER.get(ctx.public_store()).unwrap_or_default();
COUNTER.set(ctx.public_store(), counter + inc);
counter
}
}
// Implementation of the sdk::Contract trait is required in order for the type to be a contract.
impl sdk::Contract for HelloWorld {
type Request = Request;
type Response = Response;
type Error = Error;
fn instantiate<C: sdk::Context>(ctx: &mut C, request: Request) -> Result<(), Error> {
// This method is called during the contracts.Instantiate call when the contract is first
// instantiated. It can be used to initialize the contract state.
match request {
// We require the caller to always pass the Instantiate request.
Request::Instantiate { initial_counter } => {
// Initialize counter to 1.
COUNTER.set(ctx.public_store(), initial_counter);
Ok(())
}
_ => Err(Error::BadRequest),
}
}
fn call<C: sdk::Context>(ctx: &mut C, request: Request) -> Result<Response, Error> {
// This method is called for each contracts.Call call. It is supposed to handle the request
// and return a response.
match request {
Request::SayHello { who } => {
// Increment the counter and retrieve the previous value.
let counter = Self::increment_counter(ctx, 1);
// Emit a test event.
ctx.emit_event(Event::Hello("world".to_string()));
// Return the greeting as a response.
Ok(Response::Hello {
greeting: format!("hello {} ({})", who, counter),
})
}
Request::CallSelf => {
// This request is used in tests to attempt to trigger infinite recursion through
// subcalls as it invokes the same method again and again. In reality propagation
// should stop when running out of gas or reaching the maximum subcall depth.
use cbor::cbor_map;
// Emit a message through which we instruct the runtime to make a call on the
// contract's behalf. In this case we use it to call into our own contract.
//
// Any results from these calls will be processed in `handle_reply` below.
ctx.emit_message(Message::Call {
id: 0,
reply: NotifyReply::Always,
method: "contracts.Call".to_string(),
body: cbor::cbor_map! {
"id" => cbor::cbor_int!(ctx.instance_id().as_u64() as i64),
"data" => cbor::cbor_bytes!(cbor::to_vec(cbor::cbor_text!("call_self"))),
"tokens" => cbor::cbor_array![],
},
max_gas: None,
data: None,
});
Ok(Response::Empty)
}
Request::IncrementCounter => {
// Just increment the counter and return an empty response.
Self::increment_counter(ctx, 1);
Ok(Response::Empty)
}
Request::InstantiateOas20 {
code_id,
token_instantiation,
} => {
use cbor::cbor_map;
ctx.emit_message(Message::Call {
id: 42,
reply: NotifyReply::Always,
method: "contracts.Instantiate".to_string(),
body: cbor::cbor_map! {
"code_id" => cbor::cbor_int!(code_id.as_u64() as i64),
"upgrades_policy" => cbor::cbor_map!{
"everyone" => cbor::cbor_map!{},
},
"data" => cbor::cbor_bytes!(cbor::to_vec(
cbor::to_value(Oas20Request::Instantiate(token_instantiation)),
)),
// Forward any deposited native tokens, as an example of sending native tokens.
"tokens" => cbor::to_value(ctx.deposited_tokens().to_vec()),
},
max_gas: None,
data: Some(cbor::to_value("some test data".to_string())),
});
Ok(Response::Empty)
}
Request::ECDSARecover { input } => {
let output = ctx.env().ecdsa_recover(&input);
Ok(Response::ECDSARecover { output })
}
Request::QueryAddress => {
let address = ctx.env().address_for_instance(ctx.instance_id());
Ok(Response::Hello {
greeting: format!("my address is: {}", address.to_bech32()),
})
}
Request::QueryBlockInfo => match ctx.env().query(QueryRequest::BlockInfo) {
QueryResponse::BlockInfo {
round,
epoch,
timestamp,
..
} => Ok(Response::Hello {
greeting: format!("round: {} epoch: {} timestamp: {}", round, epoch, timestamp),
}),
_ => Err(Error::QueryFailed),
},
Request::QueryAccounts => match ctx.env().query(AccountsQuery::Balance {
address: *ctx.instance_address(),
denomination: token::Denomination::NATIVE,
}) {
QueryResponse::Accounts(AccountsResponse::Balance { balance }) => {
Ok(Response::Hello {
greeting: format!("my native balance is: {}", balance as u64),
})
}
_ => Err(Error::QueryFailed),
},
// Handle receiving Oas20 tokens.
Request::Oas20(ReceiverRequest::Receive {
sender: _,
amount: _,
data,
}) => {
// Just increment the counter by the amount specified in the accompanying data.
let inc: u64 = cbor::from_value(data).unwrap();
Self::increment_counter(ctx, inc);
Ok(Response::Empty)
}
_ => Err(Error::BadRequest),
}
}
fn query<C: sdk::Context>(_ctx: &mut C, _request: Request) -> Result<Response, Error> {
// This method is called for each contracts.Query query. It is supposed to handle the
// request and return a response.
Err(Error::BadRequest)
}
fn handle_reply<C: sdk::Context>(
_ctx: &mut C,
reply: Reply,
) -> Result<Option<Self::Response>, Error> {
// This method is called to handle any replies for emitted messages.
match reply {
Reply::Call { id, result, .. } if id == 0 => {
// Propagate all failures.
if !result.is_success() {
return Err(Error::SubcallFailed);
}
// Do not modify the result.
Ok(None)
}
Reply::Call { id, result, data } if id == 42 => {
let data = cbor::from_value(data.unwrap()).unwrap();
let result: InstantiateResult = match result {
CallResult::Ok(val) => Ok(cbor::from_value(val).unwrap()),
_ => Err(Error::QueryFailed),
}?;
Ok(Some(Response::InstantiateOas20 {
instance_id: result.id,
data,
}))
}
_ => Err(Error::BadRequest),
}
}
fn pre_upgrade<C: sdk::Context>(_ctx: &mut C, request: Self::Request) -> Result<(), Error> {
// This method is called on the old contract code before an upgrade is supposed to happen.
// In case it returns an error, the upgrade will be rejected.
match request {
// Allow any upgrade if request is right.
Request::UpgradeProceed | Request::UpgradeFailPost => Ok(()),
// Reject all other upgrades.
_ => Err(Error::UpgradeNotAllowedPre),
}
}
fn post_upgrade<C: sdk::Context>(_ctx: &mut C, request: Self::Request) -> Result<(), Error> {
// This method is called on the new contract code after the code has been upgraded. In case
// it returns an error, the upgrade will be rejected.
match request {
// Allow any upgrade if request is right.
Request::UpgradeProceed => Ok(()),
// Reject all other upgrades.
_ => Err(Error::UpgradeNotAllowedPost),
}
}
}
// Create the required WASM exports required for the contract to be runnable.
sdk::create_contract!(HelloWorld);
// We define some simple contract tests below.
#[cfg(test)]
mod test {
use oasis_contract_sdk::{testing::MockContext, types::ExecutionContext, Contract};
use super::*;
#[test]
fn test_hello() {
// Create a mock execution context with default values.
let mut ctx: MockContext = ExecutionContext::default().into();
// Instantiate the contract.
HelloWorld::instantiate(
&mut ctx,
Request::Instantiate {
initial_counter: 11,
},
)
.expect("instantiation should work");
// Dispatch the SayHello message.
let rsp = HelloWorld::call(
&mut ctx,
Request::SayHello {
who: "unit test".to_string(),
},
)
.expect("SayHello call should work");
// Make sure the greeting is correct.
assert_eq!(
rsp,
Response::Hello {
greeting: "hello unit test (11)".to_string()
}
);
// Dispatch another SayHello message.
let rsp = HelloWorld::call(
&mut ctx,
Request::SayHello {
who: "second call".to_string(),
},
)
.expect("SayHello call should work");
// Make sure the greeting is correct.
assert_eq!(
rsp,
Response::Hello {
greeting: "hello second call (12)".to_string()
}
);
}
}
|
// Generated by the capnpc-rust plugin to the Cap'n Proto schema compiler.
// DO NOT EDIT.
// source: helloworld.capnp
pub mod hello_world {
#![allow(unused_variables)]
pub type SayHelloParams<> = ::capnp::capability::Params<::helloworld_capnp::hello_world::say_hello_params::Owned>;
pub type SayHelloResults<> = ::capnp::capability::Results<::helloworld_capnp::hello_world::say_hello_results::Owned>;
pub struct Client {
pub client: ::capnp::capability::Client,
}
impl ::capnp::capability::FromClientHook for Client {
fn new(hook: Box<::capnp::private::capability::ClientHook>) -> Client {
Client { client: ::capnp::capability::Client::new(hook), }
}
}
#[derive(Copy, Clone)]
pub struct Owned;
impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Client; type Builder = Client; }
impl ::capnp::traits::Pipelined for Owned { type Pipeline = Client; }
impl <'a,> ::capnp::traits::FromPointerReader<'a> for Client<> {
fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> ::capnp::Result<Client<>> {
::std::result::Result::Ok(::capnp::capability::FromClientHook::new(reader.get_capability()?))
}
}
impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Client<> {
fn init_pointer(_builder: ::capnp::private::layout::PointerBuilder<'a>, _size: u32) -> Client<> {
unimplemented!()
}
fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> ::capnp::Result<Client<>> {
::std::result::Result::Ok(::capnp::capability::FromClientHook::new(builder.get_capability()?))
}
}
impl <> ::capnp::traits::SetPointerBuilder<Client<>> for Client<> {
fn set_pointer_builder(pointer: ::capnp::private::layout::PointerBuilder, from: Client<>, _canonicalize: bool) -> ::capnp::Result<()> {
pointer.set_capability(from.client.hook);
::std::result::Result::Ok(())
}
}
pub struct ToClient<U>{pub u: U}
impl <U: Server + 'static> ToClient<U> {
pub fn new(u: U) -> ToClient<U> { ToClient {u: u} }
#[deprecated(since="0.9.2", note="use into_client()")]
pub fn from_server<_T: ::capnp::private::capability::ServerHook>(self) -> Client {
self.into_client::<_T>()
}
pub fn into_client<_T: ::capnp::private::capability::ServerHook>(self) -> Client {
Client { client: _T::new_client(::std::boxed::Box::new(ServerDispatch { server: ::std::boxed::Box::new(self.u), })), }
}
}
impl ::capnp::traits::HasTypeId for Client {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl Clone for Client {
fn clone(&self) -> Client {
Client { client: ::capnp::capability::Client::new(self.client.hook.add_ref()), }
}
}
impl Client {
pub fn say_hello_request(&self) -> ::capnp::capability::Request<::helloworld_capnp::hello_world::say_hello_params::Owned,::helloworld_capnp::hello_world::say_hello_results::Owned> {
self.client.new_call(_private::TYPE_ID, 0, None)
}
}
pub trait Server<> {
fn say_hello(&mut self, _: SayHelloParams<>, _: SayHelloResults<>) -> ::capnp::capability::Promise<(), ::capnp::Error> { ::capnp::capability::Promise::err(::capnp::Error::unimplemented("method not implemented".to_string())) }
}
pub struct ServerDispatch<_T,> {
pub server: Box<_T>,
}
impl <_T: Server> ::capnp::capability::Server for ServerDispatch<_T> {
fn dispatch_call(&mut self, interface_id: u64, method_id: u16, params: ::capnp::capability::Params<::capnp::any_pointer::Owned>, results: ::capnp::capability::Results<::capnp::any_pointer::Owned>) -> ::capnp::capability::Promise<(), ::capnp::Error> {
match interface_id {
_private::TYPE_ID => ServerDispatch::<_T, >::dispatch_call_internal(&mut *self.server, method_id, params, results),
_ => { ::capnp::capability::Promise::err(::capnp::Error::unimplemented("Method not implemented.".to_string())) }
}
}
}
impl <_T :Server> ServerDispatch<_T> {
pub fn dispatch_call_internal(server: &mut _T, method_id: u16, params: ::capnp::capability::Params<::capnp::any_pointer::Owned>, results: ::capnp::capability::Results<::capnp::any_pointer::Owned>) -> ::capnp::capability::Promise<(), ::capnp::Error> {
match method_id {
0 => server.say_hello(::capnp::private::capability::internal_get_typed_params(params), ::capnp::private::capability::internal_get_typed_results(results)),
_ => { ::capnp::capability::Promise::err(::capnp::Error::unimplemented("Method not implemented.".to_string())) }
}
}
}
pub mod _private {
pub const TYPE_ID: u64 = 0x8010_72b8_b640_fa59;
}
pub mod hello_request {
#[derive(Copy, Clone)]
pub struct Owned;
impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; }
impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; }
impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; }
#[derive(Clone, Copy)]
pub struct Reader<'a> { reader: ::capnp::private::layout::StructReader<'a> }
impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> {
fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> {
Reader { reader: reader, }
}
}
impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> {
fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> ::capnp::Result<Reader<'a,>> {
::std::result::Result::Ok(::capnp::traits::FromStructReader::new(reader.get_struct(::std::ptr::null())?))
}
}
impl <'a,> ::capnp::traits::IntoInternalStructReader<'a> for Reader<'a,> {
fn into_internal_struct_reader(self) -> ::capnp::private::layout::StructReader<'a> {
self.reader
}
}
impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> {
fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) {
self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table))
}
}
impl <'a,> Reader<'a,> {
pub fn reborrow(&self) -> Reader<> {
Reader { .. *self }
}
pub fn total_size(&self) -> ::capnp::Result<::capnp::MessageSize> {
self.reader.total_size()
}
#[inline]
pub fn get_name(self) -> ::capnp::Result<::capnp::text::Reader<'a>> {
self.reader.get_pointer_field(0).get_text(::std::ptr::null(), 0)
}
pub fn has_name(&self) -> bool {
!self.reader.get_pointer_field(0).is_null()
}
}
pub struct Builder<'a> { builder: ::capnp::private::layout::StructBuilder<'a> }
impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> {
#[inline]
fn struct_size() -> ::capnp::private::layout::StructSize { _private::STRUCT_SIZE }
}
impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> {
fn new(builder: ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > {
Builder { builder: builder, }
}
}
impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> {
fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) {
self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table))
}
}
impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> {
fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size: u32) -> Builder<'a,> {
::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE))
}
fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> ::capnp::Result<Builder<'a,>> {
::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null())?))
}
}
impl <'a,> ::capnp::traits::SetPointerBuilder<Builder<'a,>> for Reader<'a,> {
fn set_pointer_builder<'b>(pointer: ::capnp::private::layout::PointerBuilder<'b>, value: Reader<'a,>, canonicalize: bool) -> ::capnp::Result<()> { pointer.set_struct(&value.reader, canonicalize) }
}
impl <'a,> Builder<'a,> {
#[deprecated(since="0.9.2", note="use into_reader()")]
pub fn as_reader(self) -> Reader<'a,> {
self.into_reader()
}
pub fn into_reader(self) -> Reader<'a,> {
::capnp::traits::FromStructReader::new(self.builder.into_reader())
}
pub fn reborrow(&mut self) -> Builder<> {
Builder { .. *self }
}
pub fn reborrow_as_reader(&self) -> Reader<> {
::capnp::traits::FromStructReader::new(self.builder.into_reader())
}
pub fn total_size(&self) -> ::capnp::Result<::capnp::MessageSize> {
self.builder.into_reader().total_size()
}
#[inline]
pub fn get_name(self) -> ::capnp::Result<::capnp::text::Builder<'a>> {
self.builder.get_pointer_field(0).get_text(::std::ptr::null(), 0)
}
#[inline]
pub fn set_name(&mut self, value: ::capnp::text::Reader) {
self.builder.get_pointer_field(0).set_text(value);
}
#[inline]
pub fn init_name(self, size: u32) -> ::capnp::text::Builder<'a> {
self.builder.get_pointer_field(0).init_text(size)
}
pub fn has_name(&self) -> bool {
!self.builder.get_pointer_field(0).is_null()
}
}
pub struct Pipeline { _typeless: ::capnp::any_pointer::Pipeline }
impl ::capnp::capability::FromTypelessPipeline for Pipeline {
fn new(typeless: ::capnp::any_pointer::Pipeline) -> Pipeline {
Pipeline { _typeless: typeless, }
}
}
impl Pipeline {
}
mod _private {
use capnp::private::layout;
pub const STRUCT_SIZE: layout::StructSize = layout::StructSize { data: 0, pointers: 1 };
pub const TYPE_ID: u64 = 0xd34a_32c4_ca81_f6c3;
}
}
pub mod hello_reply {
#[derive(Copy, Clone)]
pub struct Owned;
impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; }
impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; }
impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; }
#[derive(Clone, Copy)]
pub struct Reader<'a> { reader: ::capnp::private::layout::StructReader<'a> }
impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> {
fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> {
Reader { reader: reader, }
}
}
impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> {
fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> ::capnp::Result<Reader<'a,>> {
::std::result::Result::Ok(::capnp::traits::FromStructReader::new(reader.get_struct(::std::ptr::null())?))
}
}
impl <'a,> ::capnp::traits::IntoInternalStructReader<'a> for Reader<'a,> {
fn into_internal_struct_reader(self) -> ::capnp::private::layout::StructReader<'a> {
self.reader
}
}
impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> {
fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) {
self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table))
}
}
impl <'a,> Reader<'a,> {
pub fn reborrow(&self) -> Reader<> {
Reader { .. *self }
}
pub fn total_size(&self) -> ::capnp::Result<::capnp::MessageSize> {
self.reader.total_size()
}
#[inline]
pub fn get_message(self) -> ::capnp::Result<::capnp::text::Reader<'a>> {
self.reader.get_pointer_field(0).get_text(::std::ptr::null(), 0)
}
pub fn has_message(&self) -> bool {
!self.reader.get_pointer_field(0).is_null()
}
}
pub struct Builder<'a> { builder: ::capnp::private::layout::StructBuilder<'a> }
impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> {
#[inline]
fn struct_size() -> ::capnp::private::layout::StructSize { _private::STRUCT_SIZE }
}
impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> {
fn new(builder: ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > {
Builder { builder: builder, }
}
}
impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> {
fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) {
self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table))
}
}
impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> {
fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size: u32) -> Builder<'a,> {
::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE))
}
fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> ::capnp::Result<Builder<'a,>> {
::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null())?))
}
}
impl <'a,> ::capnp::traits::SetPointerBuilder<Builder<'a,>> for Reader<'a,> {
fn set_pointer_builder<'b>(pointer: ::capnp::private::layout::PointerBuilder<'b>, value: Reader<'a,>, canonicalize: bool) -> ::capnp::Result<()> { pointer.set_struct(&value.reader, canonicalize) }
}
impl <'a,> Builder<'a,> {
#[deprecated(since="0.9.2", note="use into_reader()")]
pub fn as_reader(self) -> Reader<'a,> {
self.into_reader()
}
pub fn into_reader(self) -> Reader<'a,> {
::capnp::traits::FromStructReader::new(self.builder.into_reader())
}
pub fn reborrow(&mut self) -> Builder<> {
Builder { .. *self }
}
pub fn reborrow_as_reader(&self) -> Reader<> {
::capnp::traits::FromStructReader::new(self.builder.into_reader())
}
pub fn total_size(&self) -> ::capnp::Result<::capnp::MessageSize> {
self.builder.into_reader().total_size()
}
#[inline]
pub fn get_message(self) -> ::capnp::Result<::capnp::text::Builder<'a>> {
self.builder.get_pointer_field(0).get_text(::std::ptr::null(), 0)
}
#[inline]
pub fn set_message(&mut self, value: ::capnp::text::Reader) {
self.builder.get_pointer_field(0).set_text(value);
}
#[inline]
pub fn init_message(self, size: u32) -> ::capnp::text::Builder<'a> {
self.builder.get_pointer_field(0).init_text(size)
}
pub fn has_message(&self) -> bool {
!self.builder.get_pointer_field(0).is_null()
}
}
pub struct Pipeline { _typeless: ::capnp::any_pointer::Pipeline }
impl ::capnp::capability::FromTypelessPipeline for Pipeline {
fn new(typeless: ::capnp::any_pointer::Pipeline) -> Pipeline {
Pipeline { _typeless: typeless, }
}
}
impl Pipeline {
}
mod _private {
use capnp::private::layout;
pub const STRUCT_SIZE: layout::StructSize = layout::StructSize { data: 0, pointers: 1 };
pub const TYPE_ID: u64 = 0xe602_9f97_7e48_df76;
}
}
pub mod say_hello_params {
#[derive(Copy, Clone)]
pub struct Owned;
impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; }
impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; }
impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; }
#[derive(Clone, Copy)]
pub struct Reader<'a> { reader: ::capnp::private::layout::StructReader<'a> }
impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> {
fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> {
Reader { reader: reader, }
}
}
impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> {
fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> ::capnp::Result<Reader<'a,>> {
::std::result::Result::Ok(::capnp::traits::FromStructReader::new(reader.get_struct(::std::ptr::null())?))
}
}
impl <'a,> ::capnp::traits::IntoInternalStructReader<'a> for Reader<'a,> {
fn into_internal_struct_reader(self) -> ::capnp::private::layout::StructReader<'a> {
self.reader
}
}
impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> {
fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) {
self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table))
}
}
impl <'a,> Reader<'a,> {
pub fn reborrow(&self) -> Reader<> {
Reader { .. *self }
}
pub fn total_size(&self) -> ::capnp::Result<::capnp::MessageSize> {
self.reader.total_size()
}
#[inline]
pub fn get_request(self) -> ::capnp::Result<::helloworld_capnp::hello_world::hello_request::Reader<'a>> {
::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(0))
}
pub fn has_request(&self) -> bool {
!self.reader.get_pointer_field(0).is_null()
}
}
pub struct Builder<'a> { builder: ::capnp::private::layout::StructBuilder<'a> }
impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> {
#[inline]
fn struct_size() -> ::capnp::private::layout::StructSize { _private::STRUCT_SIZE }
}
impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> {
fn new(builder: ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > {
Builder { builder: builder, }
}
}
impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> {
fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) {
self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table))
}
}
impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> {
fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size: u32) -> Builder<'a,> {
::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE))
}
fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> ::capnp::Result<Builder<'a,>> {
::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null())?))
}
}
impl <'a,> ::capnp::traits::SetPointerBuilder<Builder<'a,>> for Reader<'a,> {
fn set_pointer_builder<'b>(pointer: ::capnp::private::layout::PointerBuilder<'b>, value: Reader<'a,>, canonicalize: bool) -> ::capnp::Result<()> { pointer.set_struct(&value.reader, canonicalize) }
}
impl <'a,> Builder<'a,> {
#[deprecated(since="0.9.2", note="use into_reader()")]
pub fn as_reader(self) -> Reader<'a,> {
self.into_reader()
}
pub fn into_reader(self) -> Reader<'a,> {
::capnp::traits::FromStructReader::new(self.builder.into_reader())
}
pub fn reborrow(&mut self) -> Builder<> {
Builder { .. *self }
}
pub fn reborrow_as_reader(&self) -> Reader<> {
::capnp::traits::FromStructReader::new(self.builder.into_reader())
}
pub fn total_size(&self) -> ::capnp::Result<::capnp::MessageSize> {
self.builder.into_reader().total_size()
}
#[inline]
pub fn get_request(self) -> ::capnp::Result<::helloworld_capnp::hello_world::hello_request::Builder<'a>> {
::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(0))
}
#[inline]
pub fn set_request<'b>(&mut self, value: ::helloworld_capnp::hello_world::hello_request::Reader<'b>) -> ::capnp::Result<()> {
::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(0), value, false)
}
#[inline]
pub fn init_request(self, ) -> ::helloworld_capnp::hello_world::hello_request::Builder<'a> {
::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(0), 0)
}
pub fn has_request(&self) -> bool {
!self.builder.get_pointer_field(0).is_null()
}
}
pub struct Pipeline { _typeless: ::capnp::any_pointer::Pipeline }
impl ::capnp::capability::FromTypelessPipeline for Pipeline {
fn new(typeless: ::capnp::any_pointer::Pipeline) -> Pipeline {
Pipeline { _typeless: typeless, }
}
}
impl Pipeline {
pub fn get_request(&self) -> ::helloworld_capnp::hello_world::hello_request::Pipeline {
::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(0))
}
}
mod _private {
use capnp::private::layout;
pub const STRUCT_SIZE: layout::StructSize = layout::StructSize { data: 0, pointers: 1 };
pub const TYPE_ID: u64 = 0xa8af_f93e_8557_2a96;
}
}
pub mod say_hello_results {
#[derive(Copy, Clone)]
pub struct Owned;
impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; }
impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; }
impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; }
#[derive(Clone, Copy)]
pub struct Reader<'a> { reader: ::capnp::private::layout::StructReader<'a> }
impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> {
fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> {
Reader { reader: reader, }
}
}
impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> {
fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>) -> ::capnp::Result<Reader<'a,>> {
::std::result::Result::Ok(::capnp::traits::FromStructReader::new(reader.get_struct(::std::ptr::null())?))
}
}
impl <'a,> ::capnp::traits::IntoInternalStructReader<'a> for Reader<'a,> {
fn into_internal_struct_reader(self) -> ::capnp::private::layout::StructReader<'a> {
self.reader
}
}
impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> {
fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) {
self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table))
}
}
impl <'a,> Reader<'a,> {
pub fn reborrow(&self) -> Reader<> {
Reader { .. *self }
}
pub fn total_size(&self) -> ::capnp::Result<::capnp::MessageSize> {
self.reader.total_size()
}
#[inline]
pub fn get_reply(self) -> ::capnp::Result<::helloworld_capnp::hello_world::hello_reply::Reader<'a>> {
::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(0))
}
pub fn has_reply(&self) -> bool {
!self.reader.get_pointer_field(0).is_null()
}
}
pub struct Builder<'a> { builder: ::capnp::private::layout::StructBuilder<'a> }
impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> {
#[inline]
fn struct_size() -> ::capnp::private::layout::StructSize { _private::STRUCT_SIZE }
}
impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> {
#[inline]
fn type_id() -> u64 { _private::TYPE_ID }
}
impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> {
fn new(builder: ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > {
Builder { builder: builder, }
}
}
impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> {
fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) {
self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table))
}
}
impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> {
fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size: u32) -> Builder<'a,> {
::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE))
}
fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>) -> ::capnp::Result<Builder<'a,>> {
::std::result::Result::Ok(::capnp::traits::FromStructBuilder::new(builder.get_struct(_private::STRUCT_SIZE, ::std::ptr::null())?))
}
}
impl <'a,> ::capnp::traits::SetPointerBuilder<Builder<'a,>> for Reader<'a,> {
fn set_pointer_builder<'b>(pointer: ::capnp::private::layout::PointerBuilder<'b>, value: Reader<'a,>, canonicalize: bool) -> ::capnp::Result<()> { pointer.set_struct(&value.reader, canonicalize) }
}
impl <'a,> Builder<'a,> {
#[deprecated(since="0.9.2", note="use into_reader()")]
pub fn as_reader(self) -> Reader<'a,> {
self.into_reader()
}
pub fn into_reader(self) -> Reader<'a,> {
::capnp::traits::FromStructReader::new(self.builder.into_reader())
}
pub fn reborrow(&mut self) -> Builder<> {
Builder { .. *self }
}
pub fn reborrow_as_reader(&self) -> Reader<> {
::capnp::traits::FromStructReader::new(self.builder.into_reader())
}
pub fn total_size(&self) -> ::capnp::Result<::capnp::MessageSize> {
self.builder.into_reader().total_size()
}
#[inline]
pub fn get_reply(self) -> ::capnp::Result<::helloworld_capnp::hello_world::hello_reply::Builder<'a>> {
::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(0))
}
#[inline]
pub fn set_reply<'b>(&mut self, value: ::helloworld_capnp::hello_world::hello_reply::Reader<'b>) -> ::capnp::Result<()> {
::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(0), value, false)
}
#[inline]
pub fn init_reply(self, ) -> ::helloworld_capnp::hello_world::hello_reply::Builder<'a> {
::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(0), 0)
}
pub fn has_reply(&self) -> bool {
!self.builder.get_pointer_field(0).is_null()
}
}
pub struct Pipeline { _typeless: ::capnp::any_pointer::Pipeline }
impl ::capnp::capability::FromTypelessPipeline for Pipeline {
fn new(typeless: ::capnp::any_pointer::Pipeline) -> Pipeline {
Pipeline { _typeless: typeless, }
}
}
impl Pipeline {
pub fn get_reply(&self) -> ::helloworld_capnp::hello_world::hello_reply::Pipeline {
::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(0))
}
}
mod _private {
use capnp::private::layout;
pub const STRUCT_SIZE: layout::StructSize = layout::StructSize { data: 0, pointers: 1 };
pub const TYPE_ID: u64 = 0xf142_e8a9_ac34_0f88;
}
}
}
|
use std::ops::Deref;
use diesel::mysql::MysqlConnection;
use diesel::r2d2::{ConnectionManager, Pool, PoolError, PooledConnection};
use crate::model::{NewTask, Task};
pub type MyPool = Pool<ConnectionManager<MysqlConnection>>;
type MyPooledConnection = PooledConnection<ConnectionManager<MysqlConnection>>;
pub fn init_pool(database_url: &str) -> Result<MyPool, PoolError> {
let manager = ConnectionManager::<MysqlConnection>::new(database_url);
Pool::builder().build(manager)
}
fn get_conn(pool: &MyPool) -> Result<MyPooledConnection, &'static str> {
pool.get().map_err(|_| "Tidak dapat terhubung")
}
pub fn get_all_tasks(pool: &MyPool) -> Result<Vec<Task>, &'static str> {
Task::all(get_conn(pool)?.deref()).map_err(|_| "Tidak dapat insert task")
}
pub fn create_task(todo: String, pool: &MyPool) -> Result<(), &'static str> {
let new_task = NewTask { description: todo };
Task::insert(new_task, get_conn(pool)?.deref())
.map(|_| ())
.map_err(|_| "Error insert task")
}
pub fn toggle_task(id: i32, pool: &MyPool) -> Result<(), &'static str> {
Task::toggle_with_id(id, get_conn(pool)?.deref())
.map(|_| ())
.map_err(|_| "Error insert task")
}
pub fn delete_task(id: i32, pool: &MyPool) -> Result<(), &'static str> {
Task::delete_with_id(id, get_conn(pool)?.deref())
.map(|_| ())
.map_err(|_| "Error delete task")
}
|
use crate::*;
pub fn print_time() {
let start = SystemTime::now();
let datetime: DateTime<Utc> = start.into();
println!("{}", datetime.format("%d/%m/%Y %T"));
}
/// Iterates through ZoomResponse and inserts to database
pub fn save_all_meetings(data: &ZoomResponse) {
for meeting in &data.meetings {
// println!("{:#?}", &meeting);
let _successful_insert: bool = insert_meeting(meeting.clone()).is_ok();
}
}
pub fn print_stats(data: &ZoomResponse, current_page: usize) {
println!("°");
println!("├── Start \t | {}", data.from);
println!("├── End \t | {}", data.to);
println!("├── Pages \t | {:?}", data.page_count);
println!("├── Current \t | {:?}", current_page);
println!("├── Per Page \t | {:?}", data.page_size);
println!("├── Total \t | {:?}", data.total_records);
println!(
"└── Remaining \t | {:?}",
data.total_records - (data.page_count * current_page)
);
let first_item = data.meetings.first().unwrap();
println!("°");
println!("├── {}", &first_item.uuid);
println!("├── {}", &first_item.topic);
println!("├── {}", &first_item.host);
println!("├── {}", &first_item.start_time);
println!("└── {}", &first_item.end_time);
let last_item = data.meetings.last().unwrap();
println!("°");
println!("├── {}", &last_item.uuid);
println!("├── {}", &last_item.topic);
println!("├── {}", &last_item.host);
println!("├── {}", &last_item.start_time);
println!("└── {}", &last_item.end_time);
}
#[derive(FromArgs)]
/// Reach new heights.
pub struct GoUp {
/// the location of your config file
#[argh(option, short = 'c')]
pub config: String,
}
pub fn execute(key: String, secret: String, seconds_between_calls: u64) -> ZoomResults {
println!(
r#"
.oooo.o oooo ooo ooo. .oo. .ooooo. .oooo. oooooooo .ooooo. .ooooo. ooo. .oo. .oo.
d88( "8 `88. .8' `888P"Y88b d88' `"Y8 `P )88b d'""7d8P d88' `88b d88' `88b `888P"Y88bP"Y88b
`"Y88b. `88..8' 888 888 888 .oP"888 .d8P' 888 888 888 888 888 888 888
o. )88b `888' 888 888 888 .o8 d8( 888 .d8P' .P 888 888 888 888 888 888 888
8""888P' .8' o888o o888o `Y8bod8P' `Y888""8o d8888888P `Y8bod8P' `Y8bod8P' o888o o888o o888o
.o..P'
`Y8P'
"#
);
let zm_response = fetch_zoom_data(&key, &secret, None);
let mut next_page_token;
let mut current_page_number: usize = 0;
match zm_response {
Ok(data) => {
println!(
"Total Estimated Runtime {} mins\n\n",
(data.page_count * seconds_between_calls as usize) / 60
);
println!("─── Log");
print_stats(&data, 1);
save_all_meetings(&data);
next_page_token = data.next_page_token.clone();
println!("°");
println!("└── Next Page Token: {:?}\n\n", next_page_token);
thread::sleep(Duration::from_secs(seconds_between_calls)); // before we do next
for _n in 2..data.page_count + 1 {
current_page_number = _n;
let zm_response = fetch_zoom_data(&key, &secret, Some(&next_page_token));
let successful_resp: bool = match zm_response {
Ok(response) => {
println!("─── Log");
print_stats(&response, _n);
save_all_meetings(&response);
next_page_token = response.next_page_token.clone();
let mut _did = true;
if next_page_token == "" {
_did = false;
} else {
println!("°");
println!("└── Next Page Token: {:?}\n\n", next_page_token);
// wait before out next call
thread::sleep(Duration::from_secs(seconds_between_calls));
}
_did
}
Err(err) => {
println!("{:#?}", err);
false // if fail - should stop
}
};
if !successful_resp {
println!("We had an issue at page {}", _n);
break;
}
}
}
Err(err) => println!("{:#?}", err), // if fail - should stop
};
ZoomResults {
message: String::from("Finished execute"),
page_count: current_page_number,
total_records: current_page_number * 300,
}
// println!("Finished execute");
// String::from("Finished execute")
}
#[derive(Debug)]
pub struct ZoomResults {
message: String,
page_count: usize,
total_records: usize,
}
use std::fmt;
impl fmt::Display for ZoomResults {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
// let mut str = "";
// fmt.write_str(str)?;
// fmt.write_str(&self.message)?;
fmt.write_fmt(format_args!("Message: {}", self.message))?;
fmt.write_fmt(format_args!("\nPages: {}", self.page_count))?;
fmt.write_fmt(format_args!("\nRecorded: {}", self.total_records))?;
Ok(())
}
}
pub fn send_slack_message(webhook: &str, message: &str) -> String {
let final_url = webhook.to_string();
println!("Slack URL\t | {}", final_url);
let slack_message = format!("{{ \"text\": \"{}\" }}", message);
let response = minreq::post(final_url)
.with_header("Content-type", "application/json")
.with_body(slack_message)
.send()
.unwrap();
response.json().unwrap_or(String::from(""))
}
|
use crate::api::v1::ceo::order::model;
use crate::errors::ServiceError;
use crate::models::order::Order as Object;
use crate::models::DbExecutor;
use crate::schema::order::dsl::{deleted_at, id, order as tb, shop_id, state, created_at};
use actix::Handler;
use chrono::{Duration, Utc};
use crate::models::msg::Msg;
use diesel;
use diesel::prelude::*;
impl Handler<model::Update> for DbExecutor {
type Result = Result<Msg, ServiceError>;
fn handle(&mut self, msg: model::Update, _: &mut Self::Context) -> Self::Result {
let conn = &self.0.get()?;
let item_update =
diesel::update(tb.filter(&id.eq(&msg.id)).filter(&shop_id.eq(&msg.shop_id)))
.set(&msg)
.get_result::<Object>(conn)?;
let payload = serde_json::json!({
"item_update": item_update,
});
Ok(Msg {
status: 200,
data: payload,
})
}
}
impl Handler<model::Get> for DbExecutor {
type Result = Result<Msg, ServiceError>;
fn handle(&mut self, msg: model::Get, _: &mut Self::Context) -> Self::Result {
let conn = &self.0.get()?;
let item = tb.find(&msg.id).get_result::<Object>(conn)?;
let payload = serde_json::json!({
"item": item,
});
Ok(Msg {
status: 200,
data: payload,
})
}
}
impl Handler<model::GetList> for DbExecutor {
type Result = Result<Msg, ServiceError>;
fn handle(&mut self, _msg: model::GetList, _: &mut Self::Context) -> Self::Result {
let conn = &self.0.get()?;
let item = tb
.filter(&shop_id.eq(&_msg.shop_id))
.filter(&deleted_at.is_null())
.get_results::<Object>(conn)?;
let payload = serde_json::json!({
"item": item,
});
Ok(Msg {
status: 200,
data: payload,
})
}
}
impl Handler<model::NowList> for DbExecutor {
type Result = Result<Msg, ServiceError>;
fn handle(&mut self, _msg: model::NowList, _: &mut Self::Context) -> Self::Result {
let conn = &self.0.get()?;
let now2 = Utc::now().naive_utc().checked_add_signed(Duration::hours(-2)).unwrap();
let item = tb
.filter(&shop_id.eq(&_msg.shop_id))
.filter(&deleted_at.is_null())
.filter(&created_at.gt(now2))
.filter(&state.eq(1))
.or_filter(&state.eq(2))
.or_filter(&state.eq(3))
.or_filter(&state.eq(3))
.get_results::<Object>(conn)?;
let payload = serde_json::json!({
"item": item,
});
Ok(Msg {
status: 200,
data: payload,
})
}
}
|
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::f64::consts::*;
#[allow(unused)]
const INF: usize = std::usize::MAX / 4;
#[allow(unused)]
const M: usize = 1000000007;
fn factors(n: usize) -> HashSet<usize> {
let mut factors = HashSet::new();
for d in 1.. {
if d * d > n {
break;
}
if n % d == 0 {
factors.insert(d);
factors.insert(n / d);
}
}
factors
}
fn main() {
input! {
n: usize,
mut a: [usize; n],
}
let mut count = HashMap::new();
for i in 0..n {
*count.entry(a[i]).or_insert(0) += 1;
}
a.sort();
let mut f = HashSet::new();
let mut result = 0;
for i in 0..n {
if count[&a[i]] == 1 && factors(a[i]).iter().all(|&x| !f.contains(&x)) {
result += 1;
}
f.insert(a[i]);
}
println!("{}", result);
}
|
use std::time::Instant;
use rand::Rng;
mod ws_actors;
use ws_actors::{ChatWs, PairingServer, UserType};
use actix::{Actor, Addr};
use actix_files::NamedFile;
use actix_session::{CookieSession, Session};
use actix_web::{middleware, web, App, HttpRequest, HttpResponse, HttpServer, Responder};
use actix_web_actors::ws;
use serde::{Deserialize, Serialize};
use hex_literal::hex;
use sha2::{Digest, Sha256};
use structopt::StructOpt;
#[derive(Debug, Serialize, Deserialize)]
struct Credentials {
username: String,
password: String,
}
#[derive(StructOpt, Debug)]
#[structopt(name = "pychat")]
struct Opt {
#[structopt(short, long, default_value = "127.0.0.1:8080")]
address: String,
#[structopt(short, long, default_value = "5")]
max_users: usize,
}
async fn index() -> impl Responder {
NamedFile::open("./client_build/index.html")
}
fn session_is_logged_in(session: &Session) -> bool {
let is_logged_in = match session.get("isLoggedIn") {
Ok(is_logged_in) => match is_logged_in {
Some(is_logged_in) => is_logged_in,
_ => false,
},
_ => false,
};
return is_logged_in;
}
async fn login(data: web::Json<Credentials>, session: Session) -> impl Responder {
let mut hasher = Sha256::new();
hasher.input(data.0.password);
let result = hasher.result();
if data.0.username == "Teacher1"
&& result[..] == hex!("eb45d6cb783a509036744dd650a0e039f47d58cbe345ba9208c24b046287217e")
{
session.set("isLoggedIn", true).unwrap();
HttpResponse::Ok()
} else {
HttpResponse::Unauthorized().into()
}
}
async fn logout(session: Session) -> impl Responder {
match session.set("isLoggedIn", false) {
Ok(_) => HttpResponse::Ok(),
Err(_) => HttpResponse::InternalServerError(),
}
}
async fn is_logged_in(session: Session) -> impl Responder {
if session_is_logged_in(&session) {
HttpResponse::Ok()
} else {
HttpResponse::Unauthorized().into()
}
}
async fn flag(session: Session) -> impl Responder {
if session_is_logged_in(&session) {
HttpResponse::Ok().body("FLAG-06b8f0780ccd49c4be75f578aab071f3")
} else {
HttpResponse::Unauthorized().into()
}
}
async fn ws_index(
r: HttpRequest,
stream: web::Payload,
session: Session,
server: web::Data<Addr<PairingServer>>,
) -> impl Responder {
if session_is_logged_in(&session) {
println!("Teacher connection...");
ws::start(
ChatWs {
user_type: UserType::Teacher,
peer: None,
server: server.get_ref().clone(),
heartbeat: Instant::now(),
},
&r,
stream,
)
} else {
println!("Student connection...");
ws::start(
ChatWs {
user_type: UserType::Student,
peer: None,
server: server.get_ref().clone(),
heartbeat: Instant::now(),
},
&r,
stream,
)
}
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "info");
flexi_logger::Logger::with_env()
.format(flexi_logger::colored_default_format)
.start()
.unwrap();
let opt = Opt::from_args();
let server = PairingServer::new(opt.max_users).start();
let mut session_key = [0u8; 32];
rand::thread_rng().fill(&mut session_key);
HttpServer::new(move || {
App::new()
.wrap(middleware::Logger::default())
.wrap(
CookieSession::signed(&session_key)
.secure(false)
.http_only(false),
)
.app_data(web::Data::new(server.clone()))
.route("/ws", web::get().to(ws_index))
.route("/isLoggedIn", web::get().to(is_logged_in))
.route("/flag", web::get().to(flag))
.route("/", web::get().to(index))
.route("/index.html", web::get().to(index))
.route("/login", web::post().to(login))
.route("/logout", web::get().to(logout))
.service(
actix_files::Files::new("client", "client_build").disable_content_disposition(),
)
})
.bind(opt.address)?
.run()
.await
}
|
use dbgify::*;
struct Test(usize);
impl Test {
#[dbgify]
fn add_one(&mut self, x: usize) {
bp!();
self.0 += x;
}
}
fn main() {
let mut t = Test(1);
t.add_one(1usize);
}
|
use env::*;
use fun::*;
use objects::*;
use types::*;
fn init_eval(env: &mut SchemeEnv) {
//env.add_global("eval", &SchemeObject::new_prim(eval));
}
pub fn eval(obj: SchemeObject, env: &mut SchemeEnv) -> SchemeObject {
let tipe = obj.get_type();
match tipe {
SymbolType => {
let val = env.lookup_value(obj);
val.expect("eval: reference to unbound symbol: " + obj.symbol_str())
},
PairType => eval_combination(obj, env),
_ => obj.clone(),
}
}
fn eval_combination(comb: SchemeObject, env: &mut SchemeEnv) -> SchemeObject {
let rator = eval(comb.car(), env);
let tipe = rator.get_type();
match tipe {
// TODO: syntax evaluation
//SyntaxType => ,
//MacroType => ,
_ => {
let rands = comb.cdr();
let evaled_rands : ~[SchemeObject] = rands.list_iter().map(|rand| {
eval(&rand, env)
}).collect();
apply(&rator, evaled_rands)
},
}
}
// TODO: This is the scheme primitive `eval' that needs to be given an
// environment.
//fn scheme_eval(args: &[SchemeObject]) {
//if args.len() != 1 {
//fail!("eval: wrong number of arguments")
//}
//eval(&args[0], env)
//}
|
use crate::domains::schema::MockConfig;
pub trait LanguageInterpreter {
fn as_python(&self) -> String;
fn as_javascript(&self) -> String;
}
pub trait LanguageInterpreterForUnitTest {
fn as_python(&self, mock_ref: &str, mock_config: &MockConfig, target_ref: &str) -> String;
fn as_javascript(&self, mock_ref: &str, mock_config: &MockConfig, target_ref: &str) -> String;
}
|
use std::{
cell::RefCell,
hash::{Hash, Hasher},
panic::{self, AssertUnwindSafe},
rc::Rc,
};
use crate::{
callable::LuxCallable,
environment::Environment,
interpreter::{Interpreter, RuntimeResult},
literal::Literal,
stmt::Stmt,
token::Token,
};
use rand::Rng;
#[derive(PartialEq, Clone, Debug, Eq)]
pub struct Function {
pub name: Token,
pub param: Vec<Token>,
pub body: Vec<Stmt>,
}
#[derive(Clone, Debug, Eq)]
pub struct LuxFunction {
decleration: Function,
id: usize,
closure: Rc<RefCell<Environment>>,
}
impl LuxCallable for LuxFunction {
fn call(
&self,
interpreter: &mut Interpreter,
arguments: Vec<Literal>,
) -> RuntimeResult<Literal> {
let environment = Environment::new_with(self.closure.clone());
for i in 0..self.decleration.param.len() {
let name = self.decleration.param.get(i).unwrap();
let value = arguments.get(i).unwrap();
environment
.borrow_mut()
.define(name.lexeme.clone(), value.clone())
}
let hook = panic::take_hook();
panic::set_hook(Box::new(|_info| {
// do nothing
}));
let result = panic::catch_unwind(AssertUnwindSafe(|| {
interpreter.execute_block(&self.decleration.body, environment)
}));
panic::set_hook(hook);
if let Err(return_value) = result {
let casted_val = return_value.downcast::<Literal>();
if let Ok(val) = casted_val {
return Ok(*val);
}
}
Ok(Literal::Nil)
}
fn to_str(&self) -> String {
format!("<fn {}>", self.decleration.name.lexeme)
}
fn arity(&self) -> usize {
self.decleration.param.len()
}
fn id(&self) -> usize {
self.id
}
}
impl LuxFunction {
pub fn new(decleration: Function, closure: Rc<RefCell<Environment>>) -> Self {
let mut rng = rand::thread_rng();
let id: usize = rng.gen();
Self {
decleration,
id,
closure,
}
}
}
impl PartialEq for LuxFunction {
fn eq(&self, other: &Self) -> bool {
self.decleration == other.decleration
&& self.id == other.id
&& self.closure == other.closure
}
}
impl Hash for LuxFunction {
fn hash<H: Hasher>(&self, hasher: &mut H) {
// Delegate hashing to the MuseumNumber.
self.id.hash(hasher);
}
}
|
extern crate math;
use math::round;
use std::vec::Vec;
// Finds distance between two closest points in the plane by brute force
// Input: A list p of n (n >= 2) points p_1(x_1, y_1), ..., p_n(x_n, y_n)
// Output: The distance between the closest pair of points
fn brute_force_closest_pair(p: &[(f64, f64)]) -> f64 {
let n = p.len();
let mut d = f64::INFINITY;
for i in 0..(n - 1) {
for j in (i + 1)..n {
let xd = p[i].0 - p[j].0;
let yd = p[i].1 - p[j].1;
let e = xd.powi(2) + yd.powi(2);
d = d.min(e.sqrt());
}
}
d
}
// Solves the closest-pair problem by divide-and-conquer
// Input: An array p of n >= 2 points in the Cartesian plane sorted in
// nondecreasing order of their x coordinates and an array q of the same
// points sorted in nondecreasing order of the y coordinates
// Output: Euclidean distance between the closest pair of points
fn efficient_closest_pair(p: &[(f64, f64)], q: &[(f64, f64)]) -> f64 {
let n = p.len();
if n <= 3 {
return brute_force_closest_pair(p);
} else {
let nch = round::ceil(n as f64 / 2.0, 0) as usize;
let dl = efficient_closest_pair(&p[0..nch], &q[0..nch]);
let dr = efficient_closest_pair(&p[nch..n], &q[nch..n]);
let d: f64;
if dl <= dr {
d = dl;
} else {
d = dr;
}
let m = p[nch - 1].0;
let mut s = Vec::<(f64, f64)>::new();
for y_point in q {
let diff: f64 = y_point.0 - m;
if diff.abs() < d {
s.push(*y_point);
}
}
let num = s.len();
let mut dminsq: f64 = d.powi(2);
for i in 0..(num - 1) {
let mut k = i + 1;
while (k <= num - 1) && (s[k].1 - s[i].1).powi(2) < dminsq {
let e_dist: f64 = (s[k].0 - s[i].0).powi(2) + (s[k].1 - s[i].1).powi(2);
if e_dist < dminsq {
dminsq = e_dist;
}
k = k + 1;
}
}
return dminsq.sqrt();
}
}
fn main() {
let p: [(f64, f64); 4] = [(0f64, 0f64),(1f64, 1f64), (2f64, 5f64), (7f64, 3f64)];
let q: [(f64, f64); 4] = [(0f64, 0f64),(1f64, 1f64), (7f64, 3f64), (2f64, 5f64)];
println!("Points: {:?}", p);
println!("Distance between closest pair of points: {}", efficient_closest_pair(&p, &q));
}
|
use wasm::instance::{Instance, VmCtx, get_function_addr};
use wasm::{Module, ModuleEnvironment, DataInitializer};
use memory::{Region, MemFlags};
use nabi::{Result, Error};
use core::mem;
use alloc::Vec;
use nil::{Ref, KernelRef};
use cretonne_codegen::settings::{self, Configurable};
use cretonne_wasm::translate_module;
use cretonne_native;
/// A `CodeRef` represents
/// webassembly code compiled
/// into machine code. You must
/// have one of these to create
/// a process.
#[allow(dead_code)]
#[derive(KernelRef)]
pub struct CodeRef {
data_initializers: Vec<DataInitializer>,
functions: Vec<usize>,
module: Module,
region: Region,
start_func: extern fn(&VmCtx),
}
impl CodeRef {
/// Compile webassembly bytecode into a CodeRef.
pub fn compile(wasm: &[u8]) -> Result<Ref<CodeRef>> {
let (mut flag_builder, isa_builder) = cretonne_native::builders()
.map_err(|_| internal_error!())?;
flag_builder.set("opt_level", "default")
.map_err(|_| internal_error!())?;
let isa = isa_builder.finish(settings::Flags::new(flag_builder));
let module = Module::new();
let mut environ = ModuleEnvironment::new(isa.flags(), module);
translate_module(wasm, &mut environ)
.map_err(|_| internal_error!())?;
let translation = environ.finish_translation();
let (compliation, module, data_initializers) = translation.compile(&*isa)?;
compliation.emit(module, data_initializers)
}
/// Used for internal use.
pub fn new(
module: Module,
data_initializers: Vec<DataInitializer>,
mut region: Region,
start_func: *const (),
functions: Vec<usize>,
)
-> Result<Ref<CodeRef>>
{
let flags = MemFlags::READ | MemFlags::EXEC;
region.remap(flags)?;
assert!(region.contains(start_func as usize));
let start_func = unsafe {
mem::transmute(start_func)
};
Ref::new(CodeRef {
data_initializers,
module,
functions,
region,
start_func,
})
}
pub fn generate_instance(&self) -> Instance {
let code_base = self.region.start().as_ptr() as _;
Instance::new(&self.module, &self.data_initializers, code_base, &self.functions)
}
pub fn start_func(&self) -> extern fn(&VmCtx) {
self.start_func
}
pub fn lookup_func(&self, function_index: usize) -> Result<*const ()> {
let base = self.region.as_ptr() as _;
if function_index < self.functions.len() {
Ok(get_function_addr(base, &self.functions, function_index))
} else {
Err(Error::OUT_OF_BOUNDS)
}
}
}
|
mod postgrespool;
pub use self::postgrespool::DalPostgresPool;
/*
mod redispool;
pub use self::redispool::DalRedisPool;
mod dieselpool;
pub use self::dieselpool::DalDieselPool;
*/
|
/// TagName provides tags for SVG creation
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum TagName {
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/a)
A,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/animate)
Animate,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/animateMotion)
AnimateMotion,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/animateTransform)
AnimateTransform,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/circle)
Circle,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/clipPath)
ClipPath,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/color-profile)
ColorProfile,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/defs)
Defs,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/desc)
Desc,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/discard)
Discard,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/ellipse)
Ellipse,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feBlend)
FeBlend,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feColorMatrix)
FeColorMatrix,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feComponentTransfer)
FeComponentTransfer,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feComposite)
FeComposite,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feConvolveMatrix)
FeConvolveMatrix,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feDiffuseLighting)
FeDiffuseLighting,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feDisplacementMap)
FeDisplacementMap,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feDistantLight)
FeDistantLight,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feDropShadow)
FeDropShadow,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feFlood)
FeFlood,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feFuncA)
FeFuncA,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feFuncB)
FeFuncB,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feFuncG)
FeFuncG,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feFuncR)
FeFuncR,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feGaussianBlur)
FeGaussianBlur,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feImage)
FeImage,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feMerge)
FeMerge,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feMergeNode)
FeMergeNode,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feMorphology)
FeMorphology,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feOffset)
FeOffset,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/fePointLight)
FePointLight,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feSpecularLighting)
FeSpecularLighting,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feSpotLight)
FeSpotLight,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feTile)
FeTile,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/feTurbulence)
FeTurbulence,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/filter)
Filter,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject)
ForeignObject,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g)
G,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/hatch)
Hatch,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/hatchpath)
Hatchpath,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/image)
Image,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/line)
Line,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/linearGradient)
LinearGradient,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/marker)
Marker,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/mask)
Mask,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element)
Mesh,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element)
Meshgradient,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element)
Meshpatch,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element)
Meshrow,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/metadata)
Metadata,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/mpath)
Mpath,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/path)
Path,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/pattern)
Pattern,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/polygon)
Polygon,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/polyline)
Polyline,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/radialGradient)
RadialGradient,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/rect)
Rect,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/script)
Script,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/set)
Set,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/solidcolor)
Solidcolor,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/stop)
Stop,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/style)
Style,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg)
Svg,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/switch)
Switch,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/symbol)
Symbol,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/text)
Text,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/textPath)
TextPath,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/title)
Title,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/tspan)
Tspan,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element)
Unknown,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use)
Use,
/// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/view)
View,
}
// Implementation of Tagname
impl ToString for TagName {
fn to_string(&self) -> String {
use TagName::*;
String::from(match self {
A => "a",
Animate => "animate",
AnimateMotion => "animateMotion",
AnimateTransform => "animateTransform",
Circle => "circle",
ClipPath => "clipPath",
ColorProfile => "color-profile",
Defs => "defs",
Desc => "desc",
Discard => "discard",
Ellipse => "ellipse",
FeBlend => "feBlend",
FeColorMatrix => "feColorMatrix",
FeComponentTransfer => "feComponentTransfer",
FeComposite => "feComposite",
FeConvolveMatrix => "feConvolveMatrix",
FeDiffuseLighting => "feDiffuseLighting",
FeDisplacementMap => "feDisplacementMap",
FeDistantLight => "feDistantLight",
FeDropShadow => "feDropShadow",
FeFlood => "feFlood",
FeFuncA => "feFuncA",
FeFuncB => "feFuncB",
FeFuncG => "feFuncG",
FeFuncR => "feFuncR",
FeGaussianBlur => "feGaussianBlur",
FeImage => "feImage",
FeMerge => "feMerge",
FeMergeNode => "feMergeNode",
FeMorphology => "feMorphology",
FeOffset => "feOffset",
FePointLight => "fePointLight",
FeSpecularLighting => "feSpecularLighting",
FeSpotLight => "feSpotLight",
FeTile => "feTile",
FeTurbulence => "feTurbulence",
Filter => "filter",
ForeignObject => "foreignObject",
G => "g",
Hatch => "hatch",
Hatchpath => "hatchpath",
Image => "image",
Line => "line",
LinearGradient => "linearGradient",
Marker => "marker",
Mask => "mask",
Mesh => "mesh",
Meshgradient => "meshgradient",
Meshpatch => "meshpatch",
Meshrow => "meshrow",
Metadata => "metadata",
Mpath => "mpath",
Path => "path",
Pattern => "pattern",
Polygon => "polygon",
Polyline => "polyline",
RadialGradient => "radialGradient",
Rect => "rect",
Script => "script",
Set => "set",
Solidcolor => "solidcolor",
Stop => "stop",
Style => "style",
Svg => "svg",
Switch => "switch",
Symbol => "symbol",
Text => "text",
TextPath => "textPath",
Title => "title",
Tspan => "tspan",
Unknown => "unknown",
Use => "use",
View => "view",
})
}
}
|
pub fn run() {
println!("\n----- function");
fn next_birthday(name: &str, current_age: u8) {
let next_age = current_age +1;
println!("Hi {}, on your next birthday, you'll be {}!", name, next_age);
}
next_birthday("Jake", 33);
fn square(num: i32) -> i32 {
num * num
}
println!("Square of 3 is: {}", square(3))
} |
use super::{Number, Position, Size};
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Region<N: Number = f32> {
pub x: N,
pub y: N,
pub width: N,
pub height: N,
}
pub type Viewport<N = f32> = Region<N>;
impl<N: Number> Region<N> {
pub fn new(x: N, y: N, width: N, height: N) -> Self {
Self { x, y, width, height }
}
pub fn edge(left: N, right: N, top: N, bottom: N) -> Self {
Self::new(left, top, right - left, bottom - top)
}
pub fn zero() -> Self {
Self::new(N::zero(), N::zero(), N::zero(), N::zero())
}
pub fn set(&mut self, x: N, y: N, width: N, height: N) {
self.x = x;
self.y = y;
self.width = width;
self.height = height;
}
pub fn set_with(&mut self, other: &Self) {
self.x = other.x;
self.y = other.y;
self.width = other.width;
self.height = other.height;
}
pub fn left(&self) -> N {
self.x
}
pub fn set_left(&mut self, left: N) {
self.x = left;
}
pub fn right(&self) -> N {
self.x + self.width
}
pub fn set_right(&mut self, right: N) {
self.width = right - self.x;
}
pub fn top(&self) -> N {
self.y
}
pub fn set_top(&mut self, top: N) {
self.y = top;
}
pub fn bottom(&self) -> N {
self.y + self.height
}
pub fn set_bottom(&mut self, bottom: N) {
self.height = bottom - self.y;
}
pub fn set_edge(&mut self, left: N, right: N, top: N, bottom: N) {
self.set_left(left);
self.set_right(right);
self.set_top(top);
self.set_bottom(bottom);
}
pub fn top_left(&self) -> Position<N> {
Position::new(self.x, self.y)
}
pub fn top_right(&self) -> Position<N> {
Position::new(self.x + self.width, self.y)
}
pub fn bottom_left(&self) -> Position<N> {
Position::new(self.x, self.y + self.height)
}
pub fn bottom_right(&self) -> Position<N> {
Position::new(self.x + self.width, self.y + self.height)
}
pub fn position(&self) -> Position<N> {
Position::new(self.x, self.y)
}
pub fn size(&self) -> Size<N> {
Size::new(self.width, self.height)
}
}
impl<N: Number> From<(N, N, N, N)> for Region<N> {
fn from((x, y, width, height): (N, N, N, N)) -> Self {
Self::new(x, y, width, height)
}
}
impl<N: Number> Into<(N, N, N, N)> for Region<N> {
fn into(self) -> (N, N, N, N) {
(self.x, self.y, self.width, self.height)
}
}
#[cfg(test)]
mod tests {
use super::Region;
use crate::math::{Position, Size};
#[test]
fn create() {
let region = Region::<f32>::new(10.0, 20.0, 100.0, 150.0);
assert_eq!(region, Region::<f32>::edge(10.0, 110.0, 20.0, 170.0));
assert_eq!(region.left(), 10.0f32);
assert_eq!(region.right(), 110.0f32);
assert_eq!(region.top(), 20.0f32);
assert_eq!(region.bottom(), 170.0f32);
assert_eq!(region.top_left(), Position::<f32>::new(10.0, 20.0));
assert_eq!(region.top_right(), Position::<f32>::new(110.0, 20.0));
assert_eq!(region.bottom_left(), Position::<f32>::new(10.0, 170.0));
assert_eq!(region.bottom_right(), Position::<f32>::new(110.0, 170.0));
assert_eq!(region.top_left(), region.position());
assert_eq!(region.size(), Size::<f32>::new(100.0, 150.0));
}
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use std::sync::Arc;
use common_exception::ErrorCode;
use common_exception::Result;
use common_meta_app::principal::UserOptionFlag;
use once_cell::sync::Lazy;
use crate::procedures::admins::AdminProcedure;
use crate::procedures::systems::SystemProcedure;
use crate::procedures::Procedure;
pub type Factory2Creator = Box<dyn Fn() -> Result<Box<dyn Procedure>> + Send + Sync>;
#[derive(Clone, Default)]
pub struct ProcedureFeatures {
// The number of arguments the function accepts.
pub num_arguments: usize,
// (1, 2) means we only accept [1, 2] arguments
// None means it's not variadic function.
pub variadic_arguments: Option<(usize, usize)>,
// Management mode only.
pub management_mode_required: bool,
// User option flag required.
pub user_option_flag: Option<UserOptionFlag>,
}
impl ProcedureFeatures {
pub fn num_arguments(mut self, num_arguments: usize) -> ProcedureFeatures {
self.num_arguments = num_arguments;
self
}
pub fn variadic_arguments(mut self, min: usize, max: usize) -> ProcedureFeatures {
self.variadic_arguments = Some((min, max));
self
}
pub fn management_mode_required(mut self, required: bool) -> ProcedureFeatures {
self.management_mode_required = required;
self
}
pub fn user_option_flag(mut self, flag: UserOptionFlag) -> ProcedureFeatures {
self.user_option_flag = Some(flag);
self
}
}
pub struct ProcedureFactory {
creators: HashMap<String, Factory2Creator>,
}
static FUNCTION_FACTORY: Lazy<Arc<ProcedureFactory>> = Lazy::new(|| {
let mut factory = ProcedureFactory::create();
SystemProcedure::register(&mut factory);
AdminProcedure::register(&mut factory);
Arc::new(factory)
});
impl ProcedureFactory {
pub fn create() -> ProcedureFactory {
ProcedureFactory {
creators: Default::default(),
}
}
pub fn instance() -> &'static ProcedureFactory {
FUNCTION_FACTORY.as_ref()
}
pub fn register(&mut self, name: &str, creator: Factory2Creator) {
let creators = &mut self.creators;
creators.insert(name.to_lowercase(), creator);
}
pub fn get(&self, name: impl AsRef<str>) -> Result<Box<dyn Procedure>> {
let origin_name = name.as_ref();
let name = origin_name.to_lowercase();
match self.creators.get(&name) {
Some(creator) => {
let inner = creator()?;
Ok(inner)
}
None => Err(ErrorCode::UnknownFunction(format!(
"Unsupported Function: {}",
origin_name
))),
}
}
}
|
#![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::Itertools;
use whiteread::parse_line;
const ten97: usize = 1000_000_007;
/// 2の逆元 mod ten97.割りたいときに使う
const inv2ten97: u128 = 500_000_004;
fn main() {
let k: usize = parse_line().unwrap();
// dp[i]は合計がiになる数の個数
let mut dp: Vec<usize> = vec![1];
let mut i = 1;
while i <= k {
let mut tmp = 0;
for diff in 1..=9 {
if i >= diff {
tmp += dp[i - diff];
tmp %= ten97;
}
}
dp.push(tmp);
i += 1;
}
if k % 9 == 0 {
println!("{}", dp[k]);
} else {
println!("0");
}
}
|
use crate::graph::NodeItem;
use crate::to_do_list_item::ToDoListItem;
use petgraph::graph::NodeIndex;
use petgraph::visit::Dfs;
use petgraph::{Direction, Graph};
pub struct ToDoList {
graph: Box<Graph<NodeItem, ()>>,
}
impl ToDoList {
pub fn new() -> Self {
let graph = Box::new(Graph::new());
ToDoList::from_graph(graph)
}
pub fn from_graph(mut graph: Box<Graph<NodeItem, ()>>) -> Self {
graph.add_node(NodeItem::Root);
ToDoList { graph: graph }
}
pub fn add(&mut self, item: ToDoListItem, parent_: Option<usize>) -> Option<NodeIndex> {
let child = self.graph.add_node(NodeItem::Item(item));
let parent = if let Some(parent) = parent_ {
parent
} else {
0
};
self.graph.add_edge(NodeIndex::new(parent), child, ());
Some(child)
}
pub fn get(&self, id: usize) -> Option<&ToDoListItem> {
match self.graph.node_weight(NodeIndex::new(id)) {
Some(NodeItem::Item(item)) => Some(item),
_ => None,
}
}
pub fn remove(&mut self, id: usize) -> Option<usize> {
// Important: Since the index of the last node is going to change to `id` after this operation, any stored references to the last node by its index should be updated accordingly
if id == 0 {
// Prevent deletion of the root
None
} else {
let children = self.deep_children(id);
self.graph.retain_nodes(|_, node| -> bool {
children
.iter()
.position(|&i| -> bool {
let index = node.index();
i == index || id == index
})
.is_none()
});
if let Some(child) = children.get(0) {
Some(*child)
} else {
None
}
}
}
// includes the parent
pub fn deep_children(&self, id: usize) -> Vec<usize> {
let graph = &*self.graph;
let mut dfs = Dfs::new(&graph, NodeIndex::new(id));
let mut children = vec![];
while let Some(item) = dfs.next(&graph) {
children.push(item.index());
}
children
}
pub fn children(&self, index: usize) -> Vec<usize> {
let mut items = vec![];
for item in self
.graph
.neighbors_directed(NodeIndex::new(index), Direction::Outgoing)
{
items.push(item.index());
}
items.reverse();
items
}
}
#[cfg(test)]
mod tests;
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - DBGMCU_IDCODE"]
pub idcode: IDCODE,
#[doc = "0x04 - Debug MCU configuration register"]
pub cr: CR,
#[doc = "0x08 - Debug MCU APB1 freeze register1"]
pub apb_fz1: APB_FZ1,
#[doc = "0x0c - Debug MCU APB1 freeze register 2"]
pub apb_fz2: APB_FZ2,
}
#[doc = "DBGMCU_IDCODE\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [idcode](idcode) module"]
pub type IDCODE = crate::Reg<u32, _IDCODE>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _IDCODE;
#[doc = "`read()` method returns [idcode::R](idcode::R) reader structure"]
impl crate::Readable for IDCODE {}
#[doc = "DBGMCU_IDCODE"]
pub mod idcode;
#[doc = "Debug MCU configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cr](cr) module"]
pub type CR = crate::Reg<u32, _CR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CR;
#[doc = "`read()` method returns [cr::R](cr::R) reader structure"]
impl crate::Readable for CR {}
#[doc = "`write(|w| ..)` method takes [cr::W](cr::W) writer structure"]
impl crate::Writable for CR {}
#[doc = "Debug MCU configuration register"]
pub mod cr;
#[doc = "Debug MCU APB1 freeze register1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [apb_fz1](apb_fz1) module"]
pub type APB_FZ1 = crate::Reg<u32, _APB_FZ1>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _APB_FZ1;
#[doc = "`read()` method returns [apb_fz1::R](apb_fz1::R) reader structure"]
impl crate::Readable for APB_FZ1 {}
#[doc = "`write(|w| ..)` method takes [apb_fz1::W](apb_fz1::W) writer structure"]
impl crate::Writable for APB_FZ1 {}
#[doc = "Debug MCU APB1 freeze register1"]
pub mod apb_fz1;
#[doc = "Debug MCU APB1 freeze register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [apb_fz2](apb_fz2) module"]
pub type APB_FZ2 = crate::Reg<u32, _APB_FZ2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _APB_FZ2;
#[doc = "`read()` method returns [apb_fz2::R](apb_fz2::R) reader structure"]
impl crate::Readable for APB_FZ2 {}
#[doc = "`write(|w| ..)` method takes [apb_fz2::W](apb_fz2::W) writer structure"]
impl crate::Writable for APB_FZ2 {}
#[doc = "Debug MCU APB1 freeze register 2"]
pub mod apb_fz2;
|
//! Gas metering instrumentation.
use std::collections::BTreeMap;
use walrus::{ir::*, FunctionBuilder, GlobalId, LocalFunction, Module};
use crate::Error;
/// Name of the exported global that holds the gas limit.
pub const EXPORT_GAS_LIMIT: &str = "gas_limit";
/// Name of the exported global that holds the gas limit exhausted flag.
pub const EXPORT_GAS_LIMIT_EXHAUSTED: &str = "gas_limit_exhausted";
/// Configures the gas limit on the given instance.
pub fn set_gas_limit<C>(
instance: &wasm3::Instance<'_, '_, C>,
gas_limit: u64,
) -> Result<(), Error> {
instance
.set_global(EXPORT_GAS_LIMIT, gas_limit)
.map_err(|err| Error::ExecutionFailed(err.into()))
}
/// Returns the remaining gas.
pub fn get_remaining_gas<C>(instance: &wasm3::Instance<'_, '_, C>) -> u64 {
instance.get_global(EXPORT_GAS_LIMIT).unwrap_or_default()
}
/// Returns the amount of gas requested that was over the limit.
pub fn get_exhausted_amount<C>(instance: &wasm3::Instance<'_, '_, C>) -> u64 {
instance
.get_global(EXPORT_GAS_LIMIT_EXHAUSTED)
.unwrap_or_default()
}
/// Attempts to use the given amount of gas.
pub fn use_gas<C>(instance: &wasm3::Instance<'_, '_, C>, amount: u64) -> Result<(), wasm3::Trap> {
let gas_limit: u64 = instance
.get_global(EXPORT_GAS_LIMIT)
.map_err(|_| wasm3::Trap::Abort)?;
if gas_limit < amount {
let _ = instance.set_global(EXPORT_GAS_LIMIT_EXHAUSTED, amount);
return Err(wasm3::Trap::Abort);
}
instance
.set_global(EXPORT_GAS_LIMIT, gas_limit - amount)
.map_err(|_| wasm3::Trap::Abort)?;
Ok(())
}
/// Inject gas metering instrumentation into the module.
pub fn transform(module: &mut Module) {
let gas_limit_global = module.globals.add_local(
walrus::ValType::I64,
true,
walrus::InitExpr::Value(Value::I64(0)),
);
let gas_limit_exhausted_global = module.globals.add_local(
walrus::ValType::I64,
true,
walrus::InitExpr::Value(Value::I64(0)),
);
module.exports.add(EXPORT_GAS_LIMIT, gas_limit_global);
module
.exports
.add(EXPORT_GAS_LIMIT_EXHAUSTED, gas_limit_exhausted_global);
for (_, func) in module.funcs.iter_local_mut() {
transform_function(func, gas_limit_global, gas_limit_exhausted_global);
}
}
/// Instruction cost function.
fn instruction_cost(_instr: &Instr) -> u64 {
// Currently default to 1 for all instructions.
1
}
/// A block of instructions which is metered.
#[derive(Debug)]
struct MeteredBlock {
/// Instruction sequence where metering code should be injected.
seq_id: InstrSeqId,
/// Start index of instruction within the instruction sequence before which the metering code
/// should be injected.
start_index: usize,
/// Instruction cost.
cost: u64,
/// Indication of whether the metered block can be merged in case instruction sequence and start
/// index match. In case the block cannot be merged this contains the index
merge_index: Option<usize>,
}
impl MeteredBlock {
fn new(seq_id: InstrSeqId, start_index: usize) -> Self {
Self {
seq_id,
start_index,
cost: 0,
merge_index: None,
}
}
/// Create a mergable version of this metered block with the given start index.
fn mergable(&self, start_index: usize) -> Self {
Self {
seq_id: self.seq_id,
start_index,
cost: 0,
merge_index: Some(self.start_index),
}
}
}
/// A map of finalized metered blocks.
#[derive(Default)]
struct MeteredBlocks {
blocks: BTreeMap<InstrSeqId, Vec<MeteredBlock>>,
}
impl MeteredBlocks {
/// Finalize the given metered block. This means that the cost associated with the block cannot
/// change anymore.
fn finalize(&mut self, block: MeteredBlock) {
if block.cost > 0 {
self.blocks.entry(block.seq_id).or_default().push(block);
}
}
}
fn determine_metered_blocks(func: &mut LocalFunction) -> BTreeMap<InstrSeqId, Vec<MeteredBlock>> {
// NOTE: This is based on walrus::ir::dfs_in_order but we need more information.
let mut blocks = MeteredBlocks::default();
let mut stack: Vec<(InstrSeqId, usize, MeteredBlock)> = vec![(
func.entry_block(), // Initial instruction sequence to visit.
0, // Instruction offset within the sequence.
MeteredBlock::new(func.entry_block(), 0), // Initial metered block.
)];
'traversing_blocks: while let Some((seq_id, index, mut metered_block)) = stack.pop() {
let seq = func.block(seq_id);
'traversing_instrs: for (index, (instr, _)) in seq.instrs.iter().enumerate().skip(index) {
// NOTE: Current instruction is always included in the current metered block.
metered_block.cost += instruction_cost(instr);
// Determine whether we need to end/start a metered block.
match instr {
Instr::Block(Block { seq }) => {
// Do not start a new metered block as blocks are unconditional and metered
// blocks can encompass many of them to avoid injecting unnecessary
// instructions.
stack.push((seq_id, index + 1, metered_block.mergable(index + 1)));
stack.push((*seq, 0, metered_block));
continue 'traversing_blocks;
}
Instr::Loop(Loop { seq }) => {
// Finalize current metered block.
blocks.finalize(metered_block);
// Start a new metered block for remainder of block.
stack.push((seq_id, index + 1, MeteredBlock::new(seq_id, index + 1)));
// Start a new metered block for loop body.
stack.push((*seq, 0, MeteredBlock::new(*seq, 0)));
continue 'traversing_blocks;
}
Instr::IfElse(IfElse {
consequent,
alternative,
}) => {
// Finalize current metered block.
blocks.finalize(metered_block);
// Start a new metered block for remainder of block.
stack.push((seq_id, index + 1, MeteredBlock::new(seq_id, index + 1)));
// Start new metered blocks for alternative and consequent blocks.
stack.push((*alternative, 0, MeteredBlock::new(*alternative, 0)));
stack.push((*consequent, 0, MeteredBlock::new(*consequent, 0)));
continue 'traversing_blocks;
}
Instr::Call(_)
| Instr::CallIndirect(_)
| Instr::Br(_)
| Instr::BrIf(_)
| Instr::BrTable(_)
| Instr::Return(_) => {
// Finalize current metered block and start a new one for the remainder.
blocks.finalize(std::mem::replace(
&mut metered_block,
MeteredBlock::new(seq_id, index + 1),
));
continue 'traversing_instrs;
}
_ => continue 'traversing_instrs,
}
}
// Check if we can merge the blocks.
if let Some((_, _, upper)) = stack.last_mut() {
match upper.merge_index {
Some(index)
if upper.seq_id == metered_block.seq_id
&& index == metered_block.start_index =>
{
// Blocks can be merged, so overwrite upper.
*upper = metered_block;
continue 'traversing_blocks;
}
_ => {
// Blocks cannot be merged so treat as new block.
}
}
}
blocks.finalize(metered_block);
}
blocks.blocks
}
fn transform_function(
func: &mut LocalFunction,
gas_limit_global: GlobalId,
gas_limit_exhausted_global: GlobalId,
) {
// First pass: determine where metering instructions should be injected.
let blocks = determine_metered_blocks(func);
// Second pass: actually emit metering instructions in correct positions.
let builder = func.builder_mut();
for (seq_id, blocks) in blocks {
let mut seq = builder.instr_seq(seq_id);
let instrs = seq.instrs_mut();
let original_instrs = std::mem::take(instrs);
let new_instrs_len = instrs.len() + METERING_INSTRUCTION_COUNT * blocks.len();
let mut new_instrs = Vec::with_capacity(new_instrs_len);
let mut block_iter = blocks.into_iter().peekable();
for (index, (instr, loc)) in original_instrs.into_iter().enumerate() {
match block_iter.peek() {
Some(block) if block.start_index == index => {
inject_metering(
builder,
&mut new_instrs,
block_iter.next().unwrap(),
gas_limit_global,
gas_limit_exhausted_global,
);
}
_ => {}
}
// Push original instruction.
new_instrs.push((instr, loc));
}
let mut seq = builder.instr_seq(seq_id);
let instrs = seq.instrs_mut();
*instrs = new_instrs;
}
}
/// Number of injected metering instructions (needed to calculate final instruction size).
const METERING_INSTRUCTION_COUNT: usize = 8;
fn inject_metering(
builder: &mut FunctionBuilder,
instrs: &mut Vec<(Instr, InstrLocId)>,
block: MeteredBlock,
gas_limit_global: GlobalId,
gas_limit_exhausted_global: GlobalId,
) {
let mut builder = builder.dangling_instr_seq(None);
let seq = builder
// if unsigned(globals[gas_limit]) < unsigned(block.cost) { throw(); }
.global_get(gas_limit_global)
.i64_const(block.cost as i64)
.binop(BinaryOp::I64LtU)
.if_else(
None,
|then| {
then.i64_const(block.cost as i64)
.global_set(gas_limit_exhausted_global)
.unreachable();
},
|_else| {},
)
// globals[gas_limit] -= block.cost;
.global_get(gas_limit_global)
.i64_const(block.cost as i64)
.binop(BinaryOp::I64Sub)
.global_set(gas_limit_global);
instrs.append(seq.instrs_mut());
}
#[cfg(test)]
mod test {
macro_rules! test_transform {
(name = $name:ident, source = $src:expr, expected = $expected:expr) => {
#[test]
fn $name() {
let src = wat::parse_str($src).unwrap();
let expected = wat::parse_str($expected).unwrap();
let mut result_module = walrus::ModuleConfig::new()
.generate_producers_section(false)
.parse(&src)
.unwrap();
super::transform(&mut result_module);
let mut expected_module = walrus::ModuleConfig::new()
.generate_producers_section(false)
.parse(&expected)
.unwrap();
assert_eq!(result_module.emit_wasm(), expected_module.emit_wasm());
}
};
}
test_transform! {
name = simple,
source = r#"
(module
(func (result i32)
(i32.const 1)))
"#,
expected = r#"
(module
(func (result i32)
(if
(i64.lt_u
(global.get 0)
(i64.const 1))
(then
(global.set 1
(i64.const 1))
(unreachable)))
(global.set 0
(i64.sub
(global.get 0)
(i64.const 1)))
(i32.const 1))
(global (;0;) (mut i64) (i64.const 0))
(global (;1;) (mut i64) (i64.const 0))
(export "gas_limit" (global 0))
(export "gas_limit_exhausted" (global 1)))
"#
}
test_transform! {
name = nested_blocks,
source = r#"
(module
(func (result i32)
(block
(block
(block
(i32.const 1)
(drop))))
(i32.const 1)))
"#,
expected = r#"
(module
(func (result i32)
(if
(i64.lt_u
(global.get 0)
(i64.const 6))
(then
(global.set 1
(i64.const 6))
(unreachable)))
(global.set 0
(i64.sub
(global.get 0)
(i64.const 6)))
(block
(block
(block
(i32.const 1)
(drop))))
(i32.const 1))
(global (;0;) (mut i64) (i64.const 0))
(global (;1;) (mut i64) (i64.const 0))
(export "gas_limit" (global 0))
(export "gas_limit_exhausted" (global 1)))
"#
}
test_transform! {
name = nested_blocks_with_loop,
source = r#"
(module
(func (result i32)
(block
(block
(block
(i32.const 1)
(drop))
(loop
(i32.const 1)
(drop)
(i32.const 1)
(drop)
(br 0))))
(i32.const 1)))
"#,
expected = r#"
(module
(func (result i32)
(if
(i64.lt_u
(global.get 0)
(i64.const 6))
(then
(global.set 1
(i64.const 6))
(unreachable)))
(global.set 0
(i64.sub
(global.get 0)
(i64.const 6)))
(block
(block
(block
(i32.const 1)
(drop))
(loop
(if
(i64.lt_u
(global.get 0)
(i64.const 5))
(then
(global.set 1
(i64.const 5))
(unreachable)))
(global.set 0
(i64.sub
(global.get 0)
(i64.const 5)))
(i32.const 1)
(drop)
(i32.const 1)
(drop)
(br 0))))
(if
(i64.lt_u
(global.get 0)
(i64.const 1))
(then
(global.set 1
(i64.const 1))
(unreachable)))
(global.set 0
(i64.sub
(global.get 0)
(i64.const 1)))
(i32.const 1))
(global (;0;) (mut i64) (i64.const 0))
(global (;1;) (mut i64) (i64.const 0))
(export "gas_limit" (global 0))
(export "gas_limit_exhausted" (global 1)))
"#
}
test_transform! {
name = if_else,
source = r#"
(module
(func (result i32)
(i32.const 1)
(if
(then
(i32.const 1)
(drop)
(i32.const 1)
(drop))
(else
(i32.const 1)
(drop)))
(i32.const 1)))
"#,
expected = r#"
(module
(func (result i32)
(if
(i64.lt_u
(global.get 0)
(i64.const 2))
(then
(global.set 1
(i64.const 2))
(unreachable)))
(global.set 0
(i64.sub
(global.get 0)
(i64.const 2)))
(i32.const 1)
(if
(then
(if
(i64.lt_u
(global.get 0)
(i64.const 4))
(then
(global.set 1
(i64.const 4))
(unreachable)))
(global.set 0
(i64.sub
(global.get 0)
(i64.const 4)))
(i32.const 1)
(drop)
(i32.const 1)
(drop)
)
(else
(if
(i64.lt_u
(global.get 0)
(i64.const 2))
(then
(global.set 1
(i64.const 2))
(unreachable)))
(global.set 0
(i64.sub
(global.get 0)
(i64.const 2)))
(i32.const 1)
(drop)
)
)
(if
(i64.lt_u
(global.get 0)
(i64.const 1))
(then
(global.set 1
(i64.const 1))
(unreachable)))
(global.set 0
(i64.sub
(global.get 0)
(i64.const 1)))
(i32.const 1))
(global (;0;) (mut i64) (i64.const 0))
(global (;1;) (mut i64) (i64.const 0))
(export "gas_limit" (global 0))
(export "gas_limit_exhausted" (global 1)))
"#
}
}
|
// Copyright 2011 Google Inc. All Rights Reserved.
// Copyright 2017 The Ninja-rs Project Developers. All Rights Reserved.
//
// 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::path::{Path, PathBuf};
use std::collections::{HashMap, HashSet};
use std::cell::RefCell;
use std::io;
use super::disk_interface::{FileReader, FileReaderError, DiskInterface};
use super::manifest_parser::{ManifestParserOptions, ManifestParser};
use super::state::State;
use super::graph::{Node, NodeIndex};
use super::timestamp::TimeStamp;
// Support utilites for tests.
pub struct TestWithStateAndVFS<OtherData: Default> {
pub state: RefCell<State>,
pub fs: VirtualFileSystem,
pub other: OtherData,
}
impl<OtherData: Default> TestWithStateAndVFS<OtherData> {
pub fn new_minimal() -> Self {
TestWithStateAndVFS {
state: RefCell::new(State::new()),
fs: VirtualFileSystem::new(),
other: Default::default(),
}
}
pub fn new_with_builtin_rule() -> Self {
let mut test = Self::new_minimal();
test.assert_parse(
concat!("rule cat\n", " command = cat $in > $out\n").as_bytes(),
);
test
}
pub fn assert_parse_with_options(
&mut self,
input: &[u8],
options: ManifestParserOptions,
) -> () {
let mut state = self.state.borrow_mut();
{
let mut parser = ManifestParser::new(&mut state, &self.fs, options);
assert_eq!(Ok(()), parser.parse_test(input));
}
assert_eq!((), state.verify_graph());
}
pub fn assert_parse_with_options_error(
&mut self,
input: &[u8],
options: ManifestParserOptions,
err: &str,
) -> () {
let mut state = self.state.borrow_mut();
let mut parser = ManifestParser::new(&mut state, &self.fs, options);
assert_eq!(Err(err.to_owned()), parser.parse_test(input));
}
pub fn assert_parse(&mut self, input: &[u8]) -> () {
self.assert_parse_with_options(input, Default::default());
}
pub fn assert_parse_error(&mut self, input: &[u8], err: &str) -> () {
self.assert_parse_with_options_error(input, Default::default(), err);
}
pub fn assert_node_idx(&self, path: &[u8]) -> NodeIndex {
let state = self.state.borrow();
state.node_state.lookup_node(path).unwrap()
}
pub fn assert_with_node_mut<F: FnMut(&mut Node)>(&mut self, path: &[u8], mut f: F) {
let mut state = self.state.borrow_mut();
let node_idx = state.node_state.lookup_node(path).unwrap();
f(state.node_state.get_node_mut(node_idx));
}
}
/*
struct Node;
/// A base test fixture that includes a State object with a
/// builtin "cat" rule.
struct StateTestWithBuiltinRules : public testing::Test {
StateTestWithBuiltinRules();
/// Add a "cat" rule to \a state. Used by some tests; it's
/// otherwise done by the ctor to state_.
void AddCatRule(State* state);
/// Short way to get a Node by its path from state_.
Node* GetNode(const string& path);
State state_;
};
void AssertParse(State* state, const char* input,
ManifestParserOptions = ManifestParserOptions());
void AssertHash(const char* expected, uint64_t actual);
void VerifyGraph(const State& state);
*/
/// An implementation of DiskInterface that uses an in-memory representation
/// of disk state. It also logs file accesses and directory creations
/// so it can be used by tests to verify disk access patterns.
#[derive(Default)]
pub struct VirtualFileSystem {
directories_made: Vec<PathBuf>,
pub files_read: RefCell<Vec<PathBuf>>,
files: HashMap<PathBuf, VirtualFileSystemEntry>,
files_removed: HashSet<PathBuf>,
files_created: HashSet<PathBuf>,
/// A simple fake timestamp for file operations.
now: isize,
}
/// An entry for a single in-memory file.
struct VirtualFileSystemEntry {
mtime: isize,
stat_error: String, // If mtime is -1.
pub contents: Vec<u8>,
}
impl VirtualFileSystem {
pub fn new() -> Self {
let mut vfs: Self = Default::default();
vfs.now = 1isize;
vfs
}
/// Tick "time" forwards; subsequent file operations will be newer than
/// previous ones.
pub fn tick(&mut self) -> isize {
self.now += 1;
return self.now;
}
/// "Create" a file with contents.
pub fn create(&mut self, path: &Path, contents: &[u8]) {
self.files.insert(
path.to_owned(),
VirtualFileSystemEntry {
mtime: self.now,
stat_error: String::new(),
contents: contents.to_owned(),
},
);
self.files_created.insert(path.to_owned());
}
}
impl FileReader for VirtualFileSystem {
fn read_file(&self, path: &Path, contents: &mut Vec<u8>) -> Result<(), FileReaderError> {
self.files_read.borrow_mut().push(path.to_owned());
if let Some(file_contents) = self.files.get(path) {
*contents = file_contents.contents.clone();
Ok(())
} else {
Err(FileReaderError::NotFound(
"No such file or directory".to_owned(),
))
}
}
}
impl DiskInterface for VirtualFileSystem {
fn make_dir(&self, path: &Path) -> Result<(), io::Error> {
unimplemented!{}
}
fn make_dirs(&self, path: &Path) -> Result<(), io::Error> {
unimplemented!{}
}
fn stat(&self, path: &Path) -> Result<TimeStamp, String> {
unimplemented!()
}
fn write_file(&self, path: &Path, contents: &[u8]) -> Result<(), ()> {
unimplemented!()
}
fn remove_file(&self, path: &Path) -> Result<bool, io::Error> {
unimplemented!()
}
}
/*
struct VirtualFileSystem : public DiskInterface {
// DiskInterface
virtual TimeStamp Stat(const string& path, string* err) const;
virtual bool WriteFile(const string& path, const string& contents);
virtual bool MakeDir(const string& path);
virtual Status ReadFile(const string& path, string* contents, string* err);
virtual int RemoveFile(const string& path);
/// An entry for a single in-memory file.
struct Entry {
int mtime;
string stat_error; // If mtime is -1.
string contents;
};
vector<string> directories_made_;
vector<string> files_read_;
typedef map<string, Entry> FileMap;
FileMap files_;
set<string> files_removed_;
set<string> files_created_;
};
struct ScopedTempDir {
/// Create a temporary directory and chdir into it.
void CreateAndEnter(const string& name);
/// Clean up the temporary directory.
void Cleanup();
/// The temp directory containing our dir.
string start_dir_;
/// The subdirectory name for our dir, or empty if it hasn't been set up.
string temp_dir_name_;
};
#endif // NINJA_TEST_H_
*/
/*
// Copyright 2011 Google Inc. All Rights Reserved.
//
// 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.
#ifdef _WIN32
#include <direct.h> // Has to be before util.h is included.
#endif
#include "test.h"
#include <algorithm>
#include <errno.h>
#include <stdlib.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
#include "build_log.h"
#include "graph.h"
#include "manifest_parser.h"
#include "util.h"
namespace {
#ifdef _WIN32
#ifndef _mktemp_s
/// mingw has no mktemp. Implement one with the same type as the one
/// found in the Windows API.
int _mktemp_s(char* templ) {
char* ofs = strchr(templ, 'X');
sprintf(ofs, "%d", rand() % 1000000);
return 0;
}
#endif
/// Windows has no mkdtemp. Implement it in terms of _mktemp_s.
char* mkdtemp(char* name_template) {
int err = _mktemp_s(name_template);
if (err < 0) {
perror("_mktemp_s");
return NULL;
}
err = _mkdir(name_template);
if (err < 0) {
perror("mkdir");
return NULL;
}
return name_template;
}
#endif // _WIN32
string GetSystemTempDir() {
#ifdef _WIN32
char buf[1024];
if (!GetTempPath(sizeof(buf), buf))
return "";
return buf;
#else
const char* tempdir = getenv("TMPDIR");
if (tempdir)
return tempdir;
return "/tmp";
#endif
}
} // anonymous namespace
StateTestWithBuiltinRules::StateTestWithBuiltinRules() {
AddCatRule(&state_);
}
void StateTestWithBuiltinRules::AddCatRule(State* state) {
AssertParse(state,
"rule cat\n"
" command = cat $in > $out\n");
}
Node* StateTestWithBuiltinRules::GetNode(const string& path) {
EXPECT_FALSE(strpbrk(path.c_str(), "/\\"));
return state_.GetNode(path, 0);
}
void AssertParse(State* state, const char* input,
ManifestParserOptions opts) {
ManifestParser parser(state, NULL, opts);
string err;
EXPECT_TRUE(parser.ParseTest(input, &err));
ASSERT_EQ("", err);
VerifyGraph(*state);
}
void AssertHash(const char* expected, uint64_t actual) {
ASSERT_EQ(BuildLog::LogEntry::HashCommand(expected), actual);
}
void VirtualFileSystem::Create(const string& path,
const string& contents) {
files_[path].mtime = now_;
files_[path].contents = contents;
files_created_.insert(path);
}
TimeStamp VirtualFileSystem::Stat(const string& path, string* err) const {
FileMap::const_iterator i = files_.find(path);
if (i != files_.end()) {
*err = i->second.stat_error;
return i->second.mtime;
}
return 0;
}
bool VirtualFileSystem::WriteFile(const string& path, const string& contents) {
Create(path, contents);
return true;
}
bool VirtualFileSystem::MakeDir(const string& path) {
directories_made_.push_back(path);
return true; // success
}
int VirtualFileSystem::RemoveFile(const string& path) {
if (find(directories_made_.begin(), directories_made_.end(), path)
!= directories_made_.end())
return -1;
FileMap::iterator i = files_.find(path);
if (i != files_.end()) {
files_.erase(i);
files_removed_.insert(path);
return 0;
} else {
return 1;
}
}
void ScopedTempDir::CreateAndEnter(const string& name) {
// First change into the system temp dir and save it for cleanup.
start_dir_ = GetSystemTempDir();
if (start_dir_.empty())
Fatal("couldn't get system temp dir");
if (chdir(start_dir_.c_str()) < 0)
Fatal("chdir: %s", strerror(errno));
// Create a temporary subdirectory of that.
char name_template[1024];
strcpy(name_template, name.c_str());
strcat(name_template, "-XXXXXX");
char* tempname = mkdtemp(name_template);
if (!tempname)
Fatal("mkdtemp: %s", strerror(errno));
temp_dir_name_ = tempname;
// chdir into the new temporary directory.
if (chdir(temp_dir_name_.c_str()) < 0)
Fatal("chdir: %s", strerror(errno));
}
void ScopedTempDir::Cleanup() {
if (temp_dir_name_.empty())
return; // Something went wrong earlier.
// Move out of the directory we're about to clobber.
if (chdir(start_dir_.c_str()) < 0)
Fatal("chdir: %s", strerror(errno));
#ifdef _WIN32
string command = "rmdir /s /q " + temp_dir_name_;
#else
string command = "rm -rf " + temp_dir_name_;
#endif
if (system(command.c_str()) < 0)
Fatal("system: %s", strerror(errno));
temp_dir_name_.clear();
}
*/
|
// Copyright 2018 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.
extern crate tempfile;
use account_common::{
AccountAuthState, AccountManagerError, FidlAccountAuthState, FidlLocalAccountId,
LocalAccountId, ResultExt,
};
use failure::{format_err, Error};
use fidl::endpoints::{create_endpoints, ClientEnd, ServerEnd};
use fidl_fuchsia_auth::{
AppConfig, AuthState, AuthStateSummary, AuthenticationContextProviderMarker,
Status as AuthStatus,
};
use fidl_fuchsia_auth::{AuthProviderConfig, UserProfileInfo};
use fidl_fuchsia_identity_account::{
AccountListenerMarker, AccountListenerOptions, AccountManagerRequest,
AccountManagerRequestStream, AccountMarker, Error as ApiError, Lifetime,
};
use fuchsia_component::fuchsia_single_component_package_url;
use fuchsia_inspect::{Inspector, Property};
use futures::lock::Mutex;
use futures::prelude::*;
use lazy_static::lazy_static;
use log::{info, warn};
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::Arc;
use crate::account_event_emitter::{AccountEvent, AccountEventEmitter};
use crate::account_handler_connection::AccountHandlerConnection;
use crate::account_handler_context::AccountHandlerContext;
use crate::inspect;
use crate::stored_account_list::{StoredAccountList, StoredAccountMetadata};
const SELF_URL: &str = fuchsia_single_component_package_url!("account_manager");
lazy_static! {
/// The Auth scopes used for authorization during service provider-based account provisioning.
/// An empty vector means that the auth provider should use its default scopes.
static ref APP_SCOPES: Vec<String> = Vec::default();
}
/// (Temporary) A fixed AuthState that is used for all accounts until authenticators are
/// available.
const DEFAULT_AUTH_STATE: AuthState = AuthState { summary: AuthStateSummary::Unknown };
type AccountMap = BTreeMap<LocalAccountId, Option<Arc<AccountHandlerConnection>>>;
/// The core component of the account system for Fuchsia.
///
/// The AccountManager maintains the set of Fuchsia accounts that are provisioned on the device,
/// launches and configures AuthenticationProvider components to perform authentication via
/// service providers, and launches and delegates to AccountHandler component instances to
/// determine the detailed state and authentication for each account.
pub struct AccountManager {
/// An ordered map from the `LocalAccountId` of all accounts on the device to an
/// `Option` containing the `AcountHandlerConnection` used to communicate with the associated
/// AccountHandler if a connecton exists, or None otherwise.
ids_to_handlers: Mutex<AccountMap>,
/// An object to service requests for contextual information from AccountHandlers.
context: Arc<AccountHandlerContext>,
/// Contains the client ends of all AccountListeners which are subscribed to account events.
event_emitter: AccountEventEmitter,
/// Root directory containing persistent resources for an AccountManager instance.
data_dir: PathBuf,
/// Helper for outputting account information via fuchsia_inspect.
accounts_inspect: inspect::Accounts,
/// Helper for outputting auth_provider information via fuchsia_inspect. Must be retained
/// to avoid dropping the static properties it contains.
_auth_providers_inspect: inspect::AuthProviders,
}
impl AccountManager {
/// Constructs a new AccountManager, loading existing set of accounts from `data_dir`, and an
/// auth provider configuration. The directory must exist at construction.
pub fn new(
data_dir: PathBuf,
auth_provider_config: &[AuthProviderConfig],
inspector: &Inspector,
) -> Result<AccountManager, Error> {
let context = Arc::new(AccountHandlerContext::new(auth_provider_config));
// Initialize the map of Account IDs to handlers with IDs read from disk and initially no
// handlers. Account handlers will be constructed later when needed.
let mut ids_to_handlers = AccountMap::new();
let account_list = StoredAccountList::load(&data_dir)?;
for account in account_list.accounts().into_iter() {
ids_to_handlers.insert(account.account_id().clone(), None);
}
// Initialize the structs used to output state through the inspect system.
let auth_providers_inspect = inspect::AuthProviders::new(inspector.root());
let auth_provider_types: Vec<String> =
auth_provider_config.iter().map(|apc| apc.auth_provider_type.clone()).collect();
auth_providers_inspect.types.set(&auth_provider_types.join(","));
let accounts_inspect = inspect::Accounts::new(inspector.root());
accounts_inspect.total.set(ids_to_handlers.len() as u64);
let event_emitter = AccountEventEmitter::new(inspector.root());
Ok(Self {
ids_to_handlers: Mutex::new(ids_to_handlers),
context,
event_emitter,
data_dir,
accounts_inspect,
_auth_providers_inspect: auth_providers_inspect,
})
}
/// Asynchronously handles the supplied stream of `AccountManagerRequest` messages.
pub async fn handle_requests_from_stream(
&self,
mut stream: AccountManagerRequestStream,
) -> Result<(), Error> {
while let Some(req) = stream.try_next().await? {
self.handle_request(req).await?;
}
Ok(())
}
/// Handles a single request to the AccountManager.
pub async fn handle_request(&self, req: AccountManagerRequest) -> Result<(), fidl::Error> {
match req {
AccountManagerRequest::GetAccountIds { responder } => {
let mut response = self.get_account_ids().await.into_iter();
responder.send(&mut response)?;
}
AccountManagerRequest::GetAccountAuthStates { responder } => {
let mut response = self.get_account_auth_states().await;
responder.send(&mut response)?;
}
AccountManagerRequest::GetAccount { id, context_provider, account, responder } => {
let mut response = self.get_account(id.into(), context_provider, account).await;
responder.send(&mut response)?;
}
AccountManagerRequest::RegisterAccountListener { listener, options, responder } => {
let mut response = self.register_account_listener(listener, options).await;
responder.send(&mut response)?;
}
AccountManagerRequest::RemoveAccount { id, force, responder } => {
let mut response = self.remove_account(id.into(), force).await;
responder.send(&mut response)?;
}
AccountManagerRequest::ProvisionFromAuthProvider {
auth_context_provider,
auth_provider_type,
lifetime,
responder,
} => {
let mut response = self
.provision_from_auth_provider(
auth_context_provider,
auth_provider_type,
lifetime,
)
.await;
responder.send(&mut response)?;
}
AccountManagerRequest::ProvisionNewAccount { lifetime, responder } => {
let mut response = self.provision_new_account(lifetime).await;
responder.send(&mut response)?;
}
}
Ok(())
}
/// Returns an `AccountHandlerConnection` for the specified `LocalAccountId`, either by
/// returning the existing entry from the map or by creating and adding a new entry to the map.
async fn get_handler_for_existing_account<'a>(
&'a self,
ids_to_handlers: &'a mut AccountMap,
account_id: &'a LocalAccountId,
) -> Result<Arc<AccountHandlerConnection>, AccountManagerError> {
match ids_to_handlers.get(account_id) {
None => return Err(AccountManagerError::new(ApiError::NotFound)),
Some(Some(existing_handler)) => return Ok(Arc::clone(existing_handler)),
Some(None) => { /* ID is valid but a handler doesn't exist yet */ }
}
let new_handler = Arc::new(
AccountHandlerConnection::load_account(account_id, Arc::clone(&self.context)).await?,
);
ids_to_handlers.insert(account_id.clone(), Some(Arc::clone(&new_handler)));
self.accounts_inspect.active.set(count_populated(ids_to_handlers) as u64);
Ok(new_handler)
}
async fn get_account_ids(&self) -> Vec<FidlLocalAccountId> {
self.ids_to_handlers.lock().await.keys().map(|id| id.clone().into()).collect()
}
async fn get_account_auth_states(&self) -> Result<Vec<FidlAccountAuthState>, ApiError> {
// TODO(jsankey): Collect authentication state from AccountHandler instances rather than
// returning a fixed value. This will involve opening account handler connections (in
// parallel) for all of the accounts where encryption keys for the account's data partition
// are available.
let ids_to_handlers_lock = self.ids_to_handlers.lock().await;
Ok(ids_to_handlers_lock
.keys()
.map(|id| FidlAccountAuthState {
account_id: id.clone().into(),
auth_state: DEFAULT_AUTH_STATE,
})
.collect())
}
async fn get_account(
&self,
id: LocalAccountId,
auth_context_provider: ClientEnd<AuthenticationContextProviderMarker>,
account: ServerEnd<AccountMarker>,
) -> Result<(), ApiError> {
let account_handler = {
let mut ids_to_handlers = self.ids_to_handlers.lock().await;
self.get_handler_for_existing_account(&mut *ids_to_handlers, &id).await.map_err(
|err| {
warn!("Failure getting account handler connection: {:?}", err);
err.api_error
},
)?
};
account_handler.proxy().get_account(auth_context_provider, account).await.map_err(
|err| {
warn!("Failure calling get account: {:?}", err);
ApiError::Resource
},
)?
}
async fn register_account_listener(
&self,
listener: ClientEnd<AccountListenerMarker>,
options: AccountListenerOptions,
) -> Result<(), ApiError> {
let ids_to_handlers_lock = self.ids_to_handlers.lock().await;
let account_auth_states: Vec<AccountAuthState> = ids_to_handlers_lock
.keys()
// TODO(dnordstrom): Get the real auth states
.map(|id| AccountAuthState { account_id: id.clone() })
.collect();
std::mem::drop(ids_to_handlers_lock);
let proxy = listener.into_proxy().map_err(|err| {
warn!("Could not convert AccountListener client end to proxy {:?}", err);
ApiError::InvalidRequest
})?;
self.event_emitter.add_listener(proxy, options, &account_auth_states).await.map_err(|err| {
warn!("Could not instantiate AccountListener client {:?}", err);
ApiError::Unknown
})
}
async fn remove_account(
&self,
account_id: LocalAccountId,
force: bool,
) -> Result<(), ApiError> {
let mut ids_to_handlers = self.ids_to_handlers.lock().await;
let account_handler = self
.get_handler_for_existing_account(&mut *ids_to_handlers, &account_id)
.await
.map_err(|err| err.api_error)?;
account_handler.proxy().remove_account(force).await.map_err(|_| ApiError::Resource)??;
account_handler.terminate().await;
// Emphemeral accounts were never included in the StoredAccountList and so it does not need
// to be modified when they are removed.
if account_handler.get_lifetime() == &Lifetime::Persistent {
let account_ids =
Self::get_persistent_account_metadata(&ids_to_handlers, Some(&account_id));
if let Err(err) = StoredAccountList::new(account_ids).save(&self.data_dir) {
warn!("Could not save updated account list: {:?}", err);
return Err(err.api_error);
}
}
let event = AccountEvent::AccountRemoved(account_id.clone());
self.event_emitter.publish(&event).await;
ids_to_handlers.remove(&account_id);
self.accounts_inspect.total.set(ids_to_handlers.len() as u64);
self.accounts_inspect.active.set(count_populated(&ids_to_handlers) as u64);
Ok(())
}
async fn provision_new_account(
&self,
lifetime: Lifetime,
) -> Result<FidlLocalAccountId, ApiError> {
// Create an account
let (account_handler, account_id) =
match AccountHandlerConnection::create_account(Arc::clone(&self.context), lifetime)
.await
{
Ok((connection, account_id)) => (Arc::new(connection), account_id),
Err(err) => {
warn!("Failure creating account: {:?}", err);
return Err(err.api_error);
}
};
// Persist the account both in memory and on disk
if let Err(err) = self.add_account(account_handler.clone(), account_id.clone()).await {
warn!("Failure adding account: {:?}", err);
account_handler.terminate().await;
Err(err.api_error)
} else {
info!("Adding new local account {:?}", &account_id);
Ok(account_id.into())
}
}
async fn provision_from_auth_provider(
&self,
auth_context_provider: ClientEnd<AuthenticationContextProviderMarker>,
auth_provider_type: String,
lifetime: Lifetime,
) -> Result<FidlLocalAccountId, ApiError> {
// Create an account
let (account_handler, account_id) =
match AccountHandlerConnection::create_account(Arc::clone(&self.context), lifetime)
.await
{
Ok((connection, account_id)) => (Arc::new(connection), account_id),
Err(err) => {
warn!("Failure adding account: {:?}", err);
return Err(err.api_error);
}
};
// Add a service provider to the account
let _user_profile = match Self::add_service_provider_account(
auth_context_provider,
auth_provider_type,
account_handler.clone(),
)
.await
{
Ok(user_profile) => user_profile,
Err(err) => {
// TODO(dnordstrom): Remove the newly created account handler as a cleanup.
warn!("Failure adding service provider account: {:?}", err);
account_handler.terminate().await;
return Err(err.api_error);
}
};
// Persist the account both in memory and on disk
if let Err(err) = self.add_account(account_handler.clone(), account_id.clone()).await {
warn!("Failure adding service provider account: {:?}", err);
account_handler.terminate().await;
Err(err.api_error)
} else {
info!("Adding new account {:?}", &account_id);
Ok(account_id.into())
}
}
// Attach a service provider account to this Fuchsia account
async fn add_service_provider_account(
auth_context_provider: ClientEnd<AuthenticationContextProviderMarker>,
auth_provider_type: String,
account_handler: Arc<AccountHandlerConnection>,
) -> Result<UserProfileInfo, AccountManagerError> {
// Use account handler to get a channel to the account
let (account_client_end, account_server_end) =
create_endpoints().account_manager_error(ApiError::Resource)?;
account_handler.proxy().get_account(auth_context_provider, account_server_end).await??;
let account_proxy =
account_client_end.into_proxy().account_manager_error(ApiError::Resource)?;
// Use the account to get the persona
let (persona_client_end, persona_server_end) =
create_endpoints().account_manager_error(ApiError::Resource)?;
account_proxy.get_default_persona(persona_server_end).await??;
let persona_proxy =
persona_client_end.into_proxy().account_manager_error(ApiError::Resource)?;
// Use the persona to get the token manager
let (tm_client_end, tm_server_end) =
create_endpoints().account_manager_error(ApiError::Resource)?;
persona_proxy.get_token_manager(SELF_URL, tm_server_end).await??;
let tm_proxy = tm_client_end.into_proxy().account_manager_error(ApiError::Resource)?;
// Use the token manager to authorize
let mut app_config = AppConfig {
auth_provider_type,
client_id: None,
client_secret: None,
redirect_uri: None,
};
let fut = tm_proxy.authorize(
&mut app_config,
None, /* auth_ui_context */
&mut APP_SCOPES.iter().map(|x| &**x),
None, /* user_profile_id */
None, /* auth_code */
);
match fut.await? {
(AuthStatus::Ok, None) => Err(AccountManagerError::new(ApiError::Internal)
.with_cause(format_err!("Invalid response from token manager"))),
(AuthStatus::Ok, Some(user_profile)) => Ok(*user_profile),
(auth_status, _) => Err(AccountManagerError::from(auth_status)),
}
}
// Add the account to the AccountManager, including persistent state.
async fn add_account(
&self,
account_handler: Arc<AccountHandlerConnection>,
account_id: LocalAccountId,
) -> Result<(), AccountManagerError> {
let mut ids_to_handlers = self.ids_to_handlers.lock().await;
if ids_to_handlers.get(&account_id).is_some() {
// IDs are 64 bit integers that are meant to be random. Its very unlikely we'll create
// the same one twice but not impossible.
// TODO(dnordstrom): Avoid collision higher up the call chain.
return Err(AccountManagerError::new(ApiError::Unknown)
.with_cause(format_err!("Duplicate ID {:?} creating new account", &account_id)));
}
// Only persistent accounts are written to disk
if account_handler.get_lifetime() == &Lifetime::Persistent {
let mut account_ids = Self::get_persistent_account_metadata(&ids_to_handlers, None);
account_ids.push(StoredAccountMetadata::new(account_id.clone()));
if let Err(err) = StoredAccountList::new(account_ids).save(&self.data_dir) {
// TODO(dnordstrom): When AccountHandler uses persistent storage, clean up its state.
return Err(err);
}
}
ids_to_handlers.insert(account_id.clone(), Some(account_handler));
let event = AccountEvent::AccountAdded(account_id.clone());
self.event_emitter.publish(&event).await;
self.accounts_inspect.total.set(ids_to_handlers.len() as u64);
self.accounts_inspect.active.set(count_populated(&ids_to_handlers) as u64);
Ok(())
}
/// Get a vector of StoredAccountMetadata for all persistent accounts in |ids_to_handlers|,
/// optionally excluding the provided |exclude_account_id|.
fn get_persistent_account_metadata<'a>(
ids_to_handlers: &'a AccountMap,
exclude_account_id: Option<&'a LocalAccountId>,
) -> Vec<StoredAccountMetadata> {
ids_to_handlers
.iter()
.filter(|(id, handler)| {
// Filter out `exclude_account_id` if provided
exclude_account_id.map_or(true, |exclude_id| id != &exclude_id) &&
// Filter out accounts that are not persistent. Note that all accounts that do not
// have an open handler are assumed to be persistent due to the semantics of
// account lifetimes in this module.
handler.as_ref().map_or(true, |h| h.get_lifetime() == &Lifetime::Persistent)
})
.map(|(id, _)| StoredAccountMetadata::new(id.clone()))
.collect()
}
}
/// Returns the number of values in a BTreeMap of Option<> that are not None.
fn count_populated<K, V>(map: &BTreeMap<K, Option<V>>) -> usize {
map.values().filter(|v| v.is_some()).count()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::stored_account_list::{StoredAccountList, StoredAccountMetadata};
use fidl::endpoints::{create_request_stream, RequestStream};
use fidl_fuchsia_auth::AuthChangeGranularity;
use fidl_fuchsia_identity_account::{
AccountListenerRequest, AccountManagerProxy, AccountManagerRequestStream,
};
use fuchsia_async as fasync;
use fuchsia_inspect::NumericProperty;
use fuchsia_zircon as zx;
use futures::future::join;
use lazy_static::lazy_static;
use std::path::Path;
use tempfile::TempDir;
lazy_static! {
/// Configuration for a set of fake auth providers used for testing.
/// This can be populated later if needed.
static ref AUTH_PROVIDER_CONFIG: Vec<AuthProviderConfig> = {vec![]};
}
const FORCE_REMOVE_ON: bool = true;
fn request_stream_test<TestFn, Fut>(account_manager: AccountManager, test_fn: TestFn)
where
TestFn: FnOnce(AccountManagerProxy, Arc<AccountManager>) -> Fut,
Fut: Future<Output = Result<(), Error>>,
{
let mut executor = fasync::Executor::new().expect("Failed to create executor");
let (server_chan, client_chan) = zx::Channel::create().expect("Failed to create channel");
let proxy = AccountManagerProxy::new(fasync::Channel::from_channel(client_chan).unwrap());
let request_stream = AccountManagerRequestStream::from_channel(
fasync::Channel::from_channel(server_chan).unwrap(),
);
let account_manager_arc = Arc::new(account_manager);
let account_manager_clone = Arc::clone(&account_manager_arc);
fasync::spawn(async move {
account_manager_clone
.handle_requests_from_stream(request_stream)
.await
.unwrap_or_else(|err| panic!("Fatal error handling test request: {:?}", err))
});
executor
.run_singlethreaded(test_fn(proxy, account_manager_arc))
.expect("Executor run failed.")
}
// Manually contructs an account manager initialized with the supplied set of accounts.
fn create_accounts(existing_ids: Vec<u64>, data_dir: &Path) -> AccountManager {
let stored_account_list = existing_ids
.iter()
.map(|&id| StoredAccountMetadata::new(LocalAccountId::new(id)))
.collect();
StoredAccountList::new(stored_account_list)
.save(data_dir)
.expect("Couldn't write account list");
let inspector = Inspector::new();
AccountManager {
ids_to_handlers: Mutex::new(
existing_ids.into_iter().map(|id| (LocalAccountId::new(id), None)).collect(),
),
context: Arc::new(AccountHandlerContext::new(&vec![])),
event_emitter: AccountEventEmitter::new(inspector.root()),
data_dir: data_dir.to_path_buf(),
accounts_inspect: inspect::Accounts::new(inspector.root()),
_auth_providers_inspect: inspect::AuthProviders::new(inspector.root()),
}
}
// Contructs an account manager that reads its accounts from the supplied directory.
fn read_accounts(data_dir: &Path) -> AccountManager {
let inspector = Inspector::new();
AccountManager::new(data_dir.to_path_buf(), &AUTH_PROVIDER_CONFIG, &inspector).unwrap()
}
/// Note: Many AccountManager methods launch instances of an AccountHandler. Since its
/// currently not convenient to mock out this component launching in Rust, we rely on the
/// hermetic component test to provide coverage for these areas and only cover the in-process
/// behavior with this unit-test.
#[test]
fn test_new() {
let inspector = Inspector::new();
let data_dir = TempDir::new().unwrap();
request_stream_test(
AccountManager::new(data_dir.path().into(), &AUTH_PROVIDER_CONFIG, &inspector).unwrap(),
|proxy, _| {
async move {
assert_eq!(proxy.get_account_ids().await?.len(), 0);
assert_eq!(proxy.get_account_auth_states().await?, Ok(vec![]));
Ok(())
}
},
);
}
#[test]
fn test_initially_empty() {
let data_dir = TempDir::new().unwrap();
request_stream_test(create_accounts(vec![], data_dir.path()), |proxy, test_object| {
async move {
assert_eq!(proxy.get_account_ids().await?.len(), 0);
assert_eq!(proxy.get_account_auth_states().await?, Ok(vec![]));
assert_eq!(test_object.accounts_inspect.total.get().unwrap(), 0);
assert_eq!(test_object.accounts_inspect.active.get().unwrap(), 0);
Ok(())
}
});
}
#[test]
fn test_remove_missing_account() {
// Manually create an account manager with one account.
let data_dir = TempDir::new().unwrap();
let stored_account_list =
StoredAccountList::new(vec![StoredAccountMetadata::new(LocalAccountId::new(1))]);
stored_account_list.save(data_dir.path()).unwrap();
request_stream_test(read_accounts(data_dir.path()), |proxy, test_object| {
async move {
// Try to delete a very different account from the one we added.
assert_eq!(
proxy.remove_account(LocalAccountId::new(42).into(), FORCE_REMOVE_ON).await?,
Err(ApiError::NotFound)
);
assert_eq!(test_object.accounts_inspect.total.get().unwrap(), 1);
Ok(())
}
});
}
/// Sets up an AccountListener which an init event.
#[test]
fn test_account_listener() {
let mut options = AccountListenerOptions {
initial_state: true,
add_account: true,
remove_account: true,
granularity: AuthChangeGranularity { summary_changes: false },
};
let data_dir = TempDir::new().unwrap();
// TODO(dnordstrom): Use run_until_stalled macro instead.
request_stream_test(create_accounts(vec![1, 2], data_dir.path()), |proxy, _| {
async move {
let (client_end, mut stream) =
create_request_stream::<AccountListenerMarker>().unwrap();
let serve_fut = async move {
let request = stream.try_next().await.expect("stream error");
if let Some(AccountListenerRequest::OnInitialize {
account_auth_states,
responder,
}) = request
{
assert_eq!(
account_auth_states,
vec![
FidlAccountAuthState::from(&AccountAuthState {
account_id: LocalAccountId::new(1)
}),
FidlAccountAuthState::from(&AccountAuthState {
account_id: LocalAccountId::new(2)
}),
]
);
responder.send().unwrap();
} else {
panic!("Unexpected message received");
};
if let Some(_) = stream.try_next().await.expect("stream error") {
panic!("Unexpected message, channel should be closed");
}
};
let request_fut = async move {
// The registering itself triggers the init event.
assert_eq!(
proxy.register_account_listener(client_end, &mut options).await.unwrap(),
Ok(())
);
};
join(request_fut, serve_fut).await;
Ok(())
}
});
}
}
|
const N : usize = 3;
struct S {
a: u64,
b: [u64;N],
}
fn main() {
let y = Box::new (3);
let x : S = S { a: 10, b:[1,2,3]};
let mut a : u16 = 0xff00;
//let ra : &mut u16 = & mut a;
let p : * mut u16 = & mut a as * mut u16;
let p1 : * mut u8 = p as * mut u8;
unsafe {
println!("hello world {} ", *p1.offset(1) );
}
}
|
use crate::time::TimeContext;
use ecs::{ResourceRegistry, RunSystemPhase, Service, ECS};
use std::collections::hash_map::HashMap;
use std::hash::Hash;
#[derive(Eq, PartialEq, Hash)]
pub enum DebugKey {
CurrentFPS,
CameraPosition,
CurrentBlock,
BlockPos,
}
pub struct DebugInfo {
map: HashMap<DebugKey, String>,
}
pub struct FPSUpdateEvent;
impl DebugInfo {
pub fn new() -> Self {
Self {
map: HashMap::new(),
}
}
pub fn set(&mut self, key: DebugKey, value: String) {
self.map.insert(key, value);
}
pub fn get(&self, key: DebugKey) -> Option<&String> {
self.map.get(&key)
}
}
fn before_frame(resources: &mut ResourceRegistry, _value: &RunSystemPhase) {
let time_context = resources.get_mut::<TimeContext>().unwrap();
let dbg_info = resources.get_mut::<DebugInfo>().unwrap();
dbg_info.set(DebugKey::CurrentFPS, time_context.get_fps().to_string());
}
pub fn load(ecs: &mut ECS) {
ecs.resources.set(DebugInfo::new());
ecs.add_before_service(Service::at_render(before_frame));
}
|
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, TcpStream};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::thread::JoinHandle;
use std::time::Duration;
use std::{fs, io, thread};
use std::io::{Read, Write};
use std::sync::mpsc::{self, Receiver, Sender};
use nardol::prelude::{FromBytes, FromRon, IntoBytes, IntoMessage, ToRon};
use rusqlite::Connection;
use serde::{Serialize, Deserialize};
use ron::de;
use nardol::error::{NetCommsError, NetCommsErrorKind};
use shared::message::ServerReply;
use shared::{ImplementedMessage, MessageKind, RequestRaw};
use shared::user::UserLite;
use crate::command::{self, CommandRaw};
#[path ="./sql.rs"]
mod sql;
pub use sql::*;
pub enum Output {
Error(String),
FromRun(String),
FromUserInput(String),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClientConfig {
pub ip: String,
pub port: u16,
pub request_incoming_messages_timer: u64,
pub save_location: PathBuf,
}
impl ClientConfig {
pub fn new(config_location: &Path) -> Result<Self, NetCommsError> {
match fs::File::open(config_location) {
Ok(mut file) => {
let mut buffer = String::new();
if let Err(_) = file.read_to_string(&mut buffer) {
return Err(NetCommsError::new(
NetCommsErrorKind::ReadingFromFileFailed,
None));
}
match de::from_str(&buffer) {
Ok(server_settings) => return Ok(server_settings),
Err(e) => Err(NetCommsError::new(
NetCommsErrorKind::DeserializingFailed,
Some(format!("Deserializing of given RON to ServerSettings struct failed.\n{:?}", e)))),
}
},
Err(_) => return Err(NetCommsError::new(
NetCommsErrorKind::OpeningFileFailed,
None)),
}
}
}
pub fn get_user(socket: SocketAddrV4,
current_user: UserLite,
output_t: Sender<Output>) -> Result<UserLite, NetCommsError> {
output_t.send(Output::FromRun(
"Use register <username> <password> <password> or\nlogin <username> <password>\n".to_string()
)).unwrap();
let cmd_raw = command::CommandRaw::get::<String>(None);
let cmd = cmd_raw.process(current_user)?;
let request = cmd.into_message()?;
let location = Path::new("D:\\stepa\\Documents\\Rust\\net_comms_logs\\client_logs");
match TcpStream::connect(socket.clone()) {
Ok(mut stream) => {
request.send(&mut stream)?;
let msg = ImplementedMessage::receive(&mut stream, Some(location.to_path_buf()))?;
let metadata = msg.metadata();
let message_kind = metadata.message_kind();
match message_kind {
MessageKind::SeverReply => {
let server_reply = ServerReply::from_ron(&String::from_buff(&msg.content_move().into_buff())?)?;
if let ServerReply::User(user) = server_reply {
output_t.send(Output::FromRun("Successful login.".to_string())).unwrap();
return Ok(user);
} else {
println!("{:?}", server_reply);
panic!();
}
}
_ => {
todo!()
}
}
},
Err(_) => todo!(),
}
}
pub fn output(output_r: Receiver<Output>) {
thread::Builder::new().name("output".to_string()).spawn(move || {
println!("Output started.");
print!(">>> ");
io::stdout().flush().unwrap();
loop {
match output_r.recv() {
Ok(output) => {
match output {
Output::FromRun(content) => {
if !content.is_empty() {
println!("\n{}", content);
print!(">>> ");
io::stdout().flush().unwrap();
};
},
Output::Error(content) => {
if !content.is_empty() {
println!("\n[ERROR]: {}", content);
print!(">>> ");
io::stdout().flush().unwrap();
};
},
Output::FromUserInput(content) => {
if content.is_empty() {
print!(">>> ");
io::stdout().flush().unwrap();
} else {
println!("{}", content);
print!(">>> ");
io::stdout().flush().unwrap();
};
},
}
},
Err(e) => eprintln!("{}", e),
}
}
}).unwrap();
}
pub fn ip(config: &ClientConfig) -> Ipv4Addr {
match Ipv4Addr::from_str(&config.ip) {
Ok(ip) => return ip,
Err(_) => panic!("Failed to get an ip address.\nFailed to parse string from config to Ipv4Addr."),
}
}
pub fn get_waiting_messages(user: UserLite, socket: SocketAddrV4, _mpsc_transmitter: Sender<ImplementedMessage>,
request_incoming_messages_timer: u64,
save_location: &Path,
db_path: &Path,
output_t: Sender<Output>) -> JoinHandle<()> {
let db_location = db_path.to_owned();
let save_location = save_location.to_owned();
thread::Builder::new().name("GetWaitingMessages".to_string()).spawn(move || {
let mut db_conn = Connection::open(db_location).unwrap();
loop {
// Need to solve error handling. Maybe another mpsc channel?
let request = RequestRaw::GetWaitingMessagesAuto(user.clone());
let message = request.into_message().unwrap();
match TcpStream::connect(&socket) {
Ok(mut stream) => {
message.send(&mut stream).unwrap();
while let Ok(message)
= ImplementedMessage::receive(&mut stream, Some(save_location.clone())) {
let metadata = message.metadata();
let message_kind = metadata.message_kind();
let message_out = format!(
"{author} [{datetime}]: {content}",
author = message.metadata().author_username(),
datetime = message.metadata().datetime_as_string(),
content = match message_kind {
MessageKind::File => format!("Received a file {name} at {location}",
name = PathBuf::from(message.metadata().file_name().unwrap()).file_name().unwrap().to_string_lossy(),
location = PathBuf::from(message.metadata().file_name().unwrap()).to_string_lossy()
),
_ => String::from_buff(&message.content().into_buff()).unwrap()
});
output_t.send(Output::FromRun(message_out)).unwrap();
insert_message(&mut db_conn, message);
}
},
Err(_) => todo!(),
}
thread::sleep(Duration::new(request_incoming_messages_timer, 0));
}
}).unwrap()
}
pub fn process_user_input(socket: SocketAddrV4, user: UserLite, output_t: Sender<Output>) {
loop {
let cmd_raw = CommandRaw::get::<String>(None);
let cmd = cmd_raw.process(user.clone()).unwrap();
let message = cmd.into_message().unwrap();
println!("{}", message.clone().to_ron_pretty(None).unwrap());
match TcpStream::connect(&socket) {
Ok(mut stream) => {
if let Some(path) = message.metadata().file_name() {
ImplementedMessage::send_file(&mut stream, Path::new(&path)).unwrap();
} else {
message.send(&mut stream).unwrap();
}
},
Err(e) => {
println!("{}", e);
},
};
}
}
|
// Copyright 2019. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use crate::output_manager_service::{
error::OutputManagerError,
service::Balance,
storage::database::PendingTransactionOutputs,
};
use futures::{stream::Fuse, StreamExt};
use std::{collections::HashMap, fmt, time::Duration};
use tari_broadcast_channel::Subscriber;
use tari_comms::types::CommsPublicKey;
use tari_core::transactions::{
tari_amount::MicroTari,
transaction::{Transaction, TransactionInput, TransactionOutput, UnblindedOutput},
types::PrivateKey,
SenderTransactionProtocol,
};
use tari_service_framework::reply_channel::SenderService;
use tower::Service;
/// API Request enum
#[derive(Debug)]
pub enum OutputManagerRequest {
GetBalance,
AddOutput(UnblindedOutput),
GetRecipientKey((u64, MicroTari)),
GetCoinbaseKey((u64, MicroTari, u64)),
ConfirmPendingTransaction(u64),
ConfirmTransaction((u64, Vec<TransactionInput>, Vec<TransactionOutput>)),
PrepareToSendTransaction((MicroTari, MicroTari, Option<u64>, String)),
CancelTransaction(u64),
TimeoutTransactions(Duration),
GetPendingTransactions,
GetSpentOutputs,
GetUnspentOutputs,
GetInvalidOutputs,
GetSeedWords,
SetBaseNodePublicKey(CommsPublicKey),
SyncWithBaseNode,
CreateCoinSplit((MicroTari, usize, MicroTari, Option<u64>)),
}
impl fmt::Display for OutputManagerRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::GetBalance => f.write_str("GetBalance"),
Self::AddOutput(v) => f.write_str(&format!("AddOutput ({})", v.value)),
Self::GetRecipientKey(v) => f.write_str(&format!("GetRecipientKey ({})", v.0)),
Self::GetCoinbaseKey(v) => f.write_str(&format!("GetCoinbaseKey ({})", v.0)),
Self::ConfirmTransaction(v) => f.write_str(&format!("ConfirmTransaction ({})", v.0)),
Self::ConfirmPendingTransaction(v) => f.write_str(&format!("ConfirmPendingTransaction ({})", v)),
Self::PrepareToSendTransaction((_, _, _, msg)) => {
f.write_str(&format!("PrepareToSendTransaction ({})", msg))
},
Self::CancelTransaction(v) => f.write_str(&format!("CancelTransaction ({})", v)),
Self::TimeoutTransactions(d) => f.write_str(&format!("TimeoutTransactions ({}s)", d.as_secs())),
Self::GetPendingTransactions => f.write_str("GetPendingTransactions"),
Self::GetSpentOutputs => f.write_str("GetSpentOutputs"),
Self::GetUnspentOutputs => f.write_str("GetUnspentOutputs"),
Self::GetInvalidOutputs => f.write_str("GetInvalidOutputs"),
Self::GetSeedWords => f.write_str("GetSeedWords"),
Self::SetBaseNodePublicKey(k) => f.write_str(&format!("SetBaseNodePublicKey ({})", k)),
Self::SyncWithBaseNode => f.write_str("SyncWithBaseNode"),
Self::CreateCoinSplit(v) => f.write_str(&format!("CreateCoinSplit ({})", v.0)),
}
}
}
/// API Reply enum
pub enum OutputManagerResponse {
Balance(Balance),
OutputAdded,
RecipientKeyGenerated(PrivateKey),
OutputConfirmed,
PendingTransactionConfirmed,
TransactionConfirmed,
TransactionToSend(SenderTransactionProtocol),
TransactionCancelled,
TransactionsTimedOut,
PendingTransactions(HashMap<u64, PendingTransactionOutputs>),
SpentOutputs(Vec<UnblindedOutput>),
UnspentOutputs(Vec<UnblindedOutput>),
InvalidOutputs(Vec<UnblindedOutput>),
SeedWords(Vec<String>),
BaseNodePublicKeySet,
StartedBaseNodeSync(u64),
Transaction((u64, Transaction, MicroTari, MicroTari)),
}
/// Events that can be published on the Text Message Service Event Stream
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub enum OutputManagerEvent {
BaseNodeSyncRequestTimedOut(u64),
ReceiveBaseNodeResponse(u64),
Error(String),
}
#[derive(Clone)]
pub struct OutputManagerHandle {
handle: SenderService<OutputManagerRequest, Result<OutputManagerResponse, OutputManagerError>>,
event_stream: Subscriber<OutputManagerEvent>,
}
impl OutputManagerHandle {
pub fn new(
handle: SenderService<OutputManagerRequest, Result<OutputManagerResponse, OutputManagerError>>,
event_stream: Subscriber<OutputManagerEvent>,
) -> Self
{
OutputManagerHandle { handle, event_stream }
}
pub fn get_event_stream_fused(&self) -> Fuse<Subscriber<OutputManagerEvent>> {
self.event_stream.clone().fuse()
}
pub async fn add_output(&mut self, output: UnblindedOutput) -> Result<(), OutputManagerError> {
match self.handle.call(OutputManagerRequest::AddOutput(output)).await?? {
OutputManagerResponse::OutputAdded => Ok(()),
_ => Err(OutputManagerError::UnexpectedApiResponse),
}
}
pub async fn get_balance(&mut self) -> Result<Balance, OutputManagerError> {
match self.handle.call(OutputManagerRequest::GetBalance).await?? {
OutputManagerResponse::Balance(b) => Ok(b),
_ => Err(OutputManagerError::UnexpectedApiResponse),
}
}
pub async fn get_recipient_spending_key(
&mut self,
tx_id: u64,
amount: MicroTari,
) -> Result<PrivateKey, OutputManagerError>
{
match self
.handle
.call(OutputManagerRequest::GetRecipientKey((tx_id, amount)))
.await??
{
OutputManagerResponse::RecipientKeyGenerated(k) => Ok(k),
_ => Err(OutputManagerError::UnexpectedApiResponse),
}
}
pub async fn get_coinbase_spending_key(
&mut self,
tx_id: u64,
amount: MicroTari,
maturity_height: u64,
) -> Result<PrivateKey, OutputManagerError>
{
match self
.handle
.call(OutputManagerRequest::GetCoinbaseKey((tx_id, amount, maturity_height)))
.await??
{
OutputManagerResponse::RecipientKeyGenerated(k) => Ok(k),
_ => Err(OutputManagerError::UnexpectedApiResponse),
}
}
pub async fn prepare_transaction_to_send(
&mut self,
amount: MicroTari,
fee_per_gram: MicroTari,
lock_height: Option<u64>,
message: String,
) -> Result<SenderTransactionProtocol, OutputManagerError>
{
match self
.handle
.call(OutputManagerRequest::PrepareToSendTransaction((
amount,
fee_per_gram,
lock_height,
message,
)))
.await??
{
OutputManagerResponse::TransactionToSend(stp) => Ok(stp),
_ => Err(OutputManagerError::UnexpectedApiResponse),
}
}
pub async fn confirm_pending_transaction(&mut self, tx_id: u64) -> Result<(), OutputManagerError> {
match self
.handle
.call(OutputManagerRequest::ConfirmPendingTransaction(tx_id))
.await??
{
OutputManagerResponse::PendingTransactionConfirmed => Ok(()),
_ => Err(OutputManagerError::UnexpectedApiResponse),
}
}
pub async fn confirm_transaction(
&mut self,
tx_id: u64,
spent_outputs: Vec<TransactionInput>,
received_outputs: Vec<TransactionOutput>,
) -> Result<(), OutputManagerError>
{
match self
.handle
.call(OutputManagerRequest::ConfirmTransaction((
tx_id,
spent_outputs,
received_outputs,
)))
.await??
{
OutputManagerResponse::TransactionConfirmed => Ok(()),
_ => Err(OutputManagerError::UnexpectedApiResponse),
}
}
pub async fn cancel_transaction(&mut self, tx_id: u64) -> Result<(), OutputManagerError> {
match self
.handle
.call(OutputManagerRequest::CancelTransaction(tx_id))
.await??
{
OutputManagerResponse::TransactionCancelled => Ok(()),
_ => Err(OutputManagerError::UnexpectedApiResponse),
}
}
pub async fn timeout_transactions(&mut self, period: Duration) -> Result<(), OutputManagerError> {
match self
.handle
.call(OutputManagerRequest::TimeoutTransactions(period))
.await??
{
OutputManagerResponse::TransactionsTimedOut => Ok(()),
_ => Err(OutputManagerError::UnexpectedApiResponse),
}
}
pub async fn get_pending_transactions(
&mut self,
) -> Result<HashMap<u64, PendingTransactionOutputs>, OutputManagerError> {
match self.handle.call(OutputManagerRequest::GetPendingTransactions).await?? {
OutputManagerResponse::PendingTransactions(p) => Ok(p),
_ => Err(OutputManagerError::UnexpectedApiResponse),
}
}
pub async fn get_spent_outputs(&mut self) -> Result<Vec<UnblindedOutput>, OutputManagerError> {
match self.handle.call(OutputManagerRequest::GetSpentOutputs).await?? {
OutputManagerResponse::SpentOutputs(s) => Ok(s),
_ => Err(OutputManagerError::UnexpectedApiResponse),
}
}
pub async fn get_unspent_outputs(&mut self) -> Result<Vec<UnblindedOutput>, OutputManagerError> {
match self.handle.call(OutputManagerRequest::GetUnspentOutputs).await?? {
OutputManagerResponse::UnspentOutputs(s) => Ok(s),
_ => Err(OutputManagerError::UnexpectedApiResponse),
}
}
pub async fn get_invalid_outputs(&mut self) -> Result<Vec<UnblindedOutput>, OutputManagerError> {
match self.handle.call(OutputManagerRequest::GetInvalidOutputs).await?? {
OutputManagerResponse::InvalidOutputs(s) => Ok(s),
_ => Err(OutputManagerError::UnexpectedApiResponse),
}
}
pub async fn get_seed_words(&mut self) -> Result<Vec<String>, OutputManagerError> {
match self.handle.call(OutputManagerRequest::GetSeedWords).await?? {
OutputManagerResponse::SeedWords(s) => Ok(s),
_ => Err(OutputManagerError::UnexpectedApiResponse),
}
}
pub async fn set_base_node_public_key(&mut self, public_key: CommsPublicKey) -> Result<(), OutputManagerError> {
match self
.handle
.call(OutputManagerRequest::SetBaseNodePublicKey(public_key))
.await??
{
OutputManagerResponse::BaseNodePublicKeySet => Ok(()),
_ => Err(OutputManagerError::UnexpectedApiResponse),
}
}
pub async fn sync_with_base_node(&mut self) -> Result<u64, OutputManagerError> {
match self.handle.call(OutputManagerRequest::SyncWithBaseNode).await?? {
OutputManagerResponse::StartedBaseNodeSync(request_key) => Ok(request_key),
_ => Err(OutputManagerError::UnexpectedApiResponse),
}
}
pub async fn create_coin_split(
&mut self,
amount_per_split: MicroTari,
split_count: usize,
fee_per_gram: MicroTari,
lock_height: Option<u64>,
) -> Result<(u64, Transaction, MicroTari, MicroTari), OutputManagerError>
{
match self
.handle
.call(OutputManagerRequest::CreateCoinSplit((
amount_per_split,
split_count,
fee_per_gram,
lock_height,
)))
.await??
{
OutputManagerResponse::Transaction(ct) => Ok(ct),
_ => Err(OutputManagerError::UnexpectedApiResponse),
}
}
}
|
//! gRPC service for getting files from the object store a remote IOx service is connected to. Used
//! in router, but can be included in any gRPC server.
#![deny(rustdoc::broken_intra_doc_links, rustdoc::bare_urls, rust_2018_idioms)]
#![warn(
missing_copy_implementations,
missing_debug_implementations,
missing_docs,
clippy::explicit_iter_loop,
// See https://github.com/influxdata/influxdb_iox/pull/1671
clippy::future_not_send,
clippy::use_self,
clippy::clone_on_ref_ptr,
clippy::todo,
clippy::dbg_macro,
unused_crate_dependencies
)]
// Workaround for "unused crate" lint false positives.
use workspace_hack as _;
use futures::{stream::BoxStream, StreamExt};
use generated_types::influxdata::iox::object_store::v1::*;
use iox_catalog::interface::Catalog;
use object_store::DynObjectStore;
use observability_deps::tracing::*;
use parquet_file::ParquetFilePath;
use std::sync::Arc;
use tonic::{Request, Response, Status};
use uuid::Uuid;
/// Implementation of the ObjectStore gRPC service
#[derive(Debug)]
pub struct ObjectStoreService {
/// Catalog
catalog: Arc<dyn Catalog>,
/// The object store
object_store: Arc<DynObjectStore>,
}
impl ObjectStoreService {
/// Create a new object store service with the given catalog and object store
pub fn new(catalog: Arc<dyn Catalog>, object_store: Arc<DynObjectStore>) -> Self {
Self {
catalog,
object_store,
}
}
}
#[tonic::async_trait]
impl object_store_service_server::ObjectStoreService for ObjectStoreService {
type GetParquetFileByObjectStoreIdStream =
BoxStream<'static, Result<GetParquetFileByObjectStoreIdResponse, Status>>;
async fn get_parquet_file_by_object_store_id(
&self,
request: Request<GetParquetFileByObjectStoreIdRequest>,
) -> Result<Response<Self::GetParquetFileByObjectStoreIdStream>, Status> {
let mut repos = self.catalog.repositories().await;
let req = request.into_inner();
let object_store_id =
Uuid::parse_str(&req.uuid).map_err(|e| Status::invalid_argument(e.to_string()))?;
let parquet_file = repos
.parquet_files()
.get_by_object_store_id(object_store_id)
.await
.map_err(|e| {
warn!(error=%e, %req.uuid, "failed to get parquet_file by object store id");
Status::unknown(e.to_string())
})?
.ok_or_else(|| Status::not_found(req.uuid))?;
let path = ParquetFilePath::new(
parquet_file.namespace_id,
parquet_file.table_id,
&parquet_file.partition_id.clone(),
parquet_file.object_store_id,
);
let path = path.object_store_path();
let res = self
.object_store
.get(&path)
.await
.map_err(|e| Status::unknown(e.to_string()))?;
let rx = Box::pin(res.into_stream().map(|next| match next {
Ok(data) => Ok(GetParquetFileByObjectStoreIdResponse {
data: data.to_vec(),
}),
Err(e) => Err(Status::unknown(e.to_string())),
}));
Ok(Response::new(rx))
}
}
#[cfg(test)]
mod tests {
use super::*;
use bytes::Bytes;
use data_types::{ColumnId, ColumnSet, CompactionLevel, ParquetFileParams, Timestamp};
use generated_types::influxdata::iox::object_store::v1::object_store_service_server::ObjectStoreService;
use iox_catalog::{
mem::MemCatalog,
test_helpers::{arbitrary_namespace, arbitrary_table},
};
use object_store::{memory::InMemory, ObjectStore};
use uuid::Uuid;
#[tokio::test]
async fn test_get_parquet_file_by_object_store_id() {
// create a catalog and populate it with some test data, then drop the write lock
let p1;
let catalog = {
let metrics = Arc::new(metric::Registry::default());
let catalog = Arc::new(MemCatalog::new(metrics));
let mut repos = catalog.repositories().await;
let namespace = arbitrary_namespace(&mut *repos, "catalog_partition_test").await;
let table = arbitrary_table(&mut *repos, "schema_test_table", &namespace).await;
let partition = repos
.partitions()
.create_or_get("foo".into(), table.id)
.await
.unwrap();
let p1params = ParquetFileParams {
namespace_id: namespace.id,
table_id: table.id,
partition_id: partition.transition_partition_id(),
object_store_id: Uuid::new_v4(),
min_time: Timestamp::new(1),
max_time: Timestamp::new(5),
file_size_bytes: 2343,
row_count: 29,
compaction_level: CompactionLevel::Initial,
created_at: Timestamp::new(2343),
column_set: ColumnSet::new([ColumnId::new(1), ColumnId::new(2)]),
max_l0_created_at: Timestamp::new(2343),
};
p1 = repos.parquet_files().create(p1params).await.unwrap();
Arc::clone(&catalog)
};
let object_store = Arc::new(InMemory::new());
let path = ParquetFilePath::new(
p1.namespace_id,
p1.table_id,
&p1.partition_id.clone(),
p1.object_store_id,
);
let path = path.object_store_path();
let data = Bytes::from_static(b"some data");
object_store.put(&path, data.clone()).await.unwrap();
let grpc = super::ObjectStoreService::new(catalog, object_store);
let request = GetParquetFileByObjectStoreIdRequest {
uuid: p1.object_store_id.to_string(),
};
let tonic_response = grpc
.get_parquet_file_by_object_store_id(Request::new(request))
.await
.expect("rpc request should succeed");
let mut response = tonic_response.into_inner();
let response = response.next().await.unwrap().unwrap();
assert_eq!(response.data, data);
}
}
|
// Play a sound when a button is clicked
extern crate quicksilver;
use quicksilver::{
Result,
geom::{Rectangle, Shape, Vector},
graphics::{Background::Col, Color},
input::{ButtonState, MouseButton},
lifecycle::{Asset, Settings, State, Window, run},
sound::Sound
};
struct SoundPlayer {
asset: Asset<Sound>,
}
const BUTTON_AREA: Rectangle = Rectangle {
pos: Vector {x: 350.0, y: 250.0},
size: Vector {x: 100.0, y: 100.0}
};
impl State for SoundPlayer {
fn new() -> Result<SoundPlayer> {
let asset = Asset::new(Sound::load("boop.ogg"));
Ok(SoundPlayer { asset })
}
fn update(&mut self, window: &mut Window) -> Result<()> {
self.asset.execute(|sound| {
if window.mouse()[MouseButton::Left] == ButtonState::Pressed
&& BUTTON_AREA.contains(window.mouse().pos()) {
sound.play()?;
}
Ok(())
})
}
fn draw(&mut self, window: &mut Window) -> Result<()> {
window.clear(Color::WHITE)?;
// If the sound is loaded, draw the button
self.asset.execute(|_| {
window.draw(&BUTTON_AREA, Col(Color::BLUE));
Ok(())
})
}
}
fn main() {
run::<SoundPlayer>("Sound example", Vector::new(800, 600), Settings::default());
}
|
//主函数
fn main() {
//println!("Hello, world!");
// 定义病初始化一个变量var1
let var1 = 1;
//打印格式化文本并在结尾输出换行
println!("{}",var1);
//对不可变变量重新赋值--->会报错
var1 = 2;
println!("{}",var1);
}
|
use base64;
use bitcoin::blockdata::block::Block;
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::consensus::encode;
use bitcoin::hash_types::{BlockHash, Txid};
use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
use lightning_block_sync::http::HttpEndpoint;
use lightning_block_sync::rpc::RpcClient;
use lightning_block_sync::{AsyncBlockSourceResult, BlockHeaderData, BlockSource};
use serde_json;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use std::time::Duration;
use bitcoin::hashes::hex::FromHex;
use lightning_block_sync::http::JsonResponse;
use std::convert::TryInto;
pub struct FeeResponse {
pub feerate_sat_per_kw: Option<u32>,
pub errored: bool,
}
impl TryInto<FeeResponse> for JsonResponse {
type Error = std::io::Error;
fn try_into(self) -> std::io::Result<FeeResponse> {
let errored = !self.0["errors"].is_null();
Ok(FeeResponse {
errored,
feerate_sat_per_kw: self.0["feerate"].as_f64().map(|feerate_btc_per_kvbyte| {
// Bitcoin Core gives us a feerate in BTC/KvB, which we need to convert to
// satoshis/KW. Thus, we first multiply by 10^8 to get satoshis, then divide by 4
// to convert virtual-bytes into weight units.
(feerate_btc_per_kvbyte * 100_000_000.0 / 4.0).round() as u32
}),
})
}
}
pub struct BlockchainInfo {
pub latest_height: usize,
pub latest_blockhash: BlockHash,
pub chain: String,
}
impl TryInto<BlockchainInfo> for JsonResponse {
type Error = std::io::Error;
fn try_into(self) -> std::io::Result<BlockchainInfo> {
Ok(BlockchainInfo {
latest_height: self.0["blocks"].as_u64().unwrap() as usize,
latest_blockhash: BlockHash::from_hex(self.0["bestblockhash"].as_str().unwrap())
.unwrap(),
chain: self.0["chain"].as_str().unwrap().to_string(),
})
}
}
pub struct BitcoindClient {
bitcoind_rpc_client: Arc<RpcClient>,
fees: Arc<HashMap<Target, AtomicU32>>,
handle: tokio::runtime::Handle,
}
#[derive(Clone, Eq, Hash, PartialEq)]
pub enum Target {
Background,
Normal,
HighPriority,
}
impl BlockSource for BitcoindClient {
fn get_header<'a>(
&'a self,
header_hash: &'a BlockHash,
height_hint: Option<u32>,
) -> AsyncBlockSourceResult<'a, BlockHeaderData> {
Box::pin(async move {
self.bitcoind_rpc_client
.get_header(header_hash, height_hint)
.await
})
}
fn get_block<'a>(&'a self, header_hash: &'a BlockHash) -> AsyncBlockSourceResult<'a, Block> {
Box::pin(async move { self.bitcoind_rpc_client.get_block(header_hash).await })
}
fn get_best_block(&self) -> AsyncBlockSourceResult<(BlockHash, Option<u32>)> {
Box::pin(async move { self.bitcoind_rpc_client.get_best_block().await })
}
}
/// The minimum feerate we are allowed to send, as specify by LDK.
const MIN_FEERATE: u32 = 253;
impl BitcoindClient {
pub async fn new(
host: String,
port: u16,
rpc_user: String,
rpc_password: String,
handle: tokio::runtime::Handle,
) -> std::io::Result<Self> {
let http_endpoint = HttpEndpoint::for_host(host.clone()).with_port(port);
let rpc_credentials =
base64::encode(format!("{}:{}", rpc_user.clone(), rpc_password.clone()));
let bitcoind_rpc_client = RpcClient::new(&rpc_credentials, http_endpoint)?;
let _dummy = bitcoind_rpc_client
.call_method::<BlockchainInfo>("getblockchaininfo", &[])
.await
.map_err(|_| {
std::io::Error::new(std::io::ErrorKind::PermissionDenied,
"Failed to make initial call to bitcoind - please check your RPC user/password and access settings")
})?;
let mut fees: HashMap<Target, AtomicU32> = HashMap::new();
fees.insert(Target::Background, AtomicU32::new(MIN_FEERATE));
fees.insert(Target::Normal, AtomicU32::new(2000)); // 8 sats per byte
fees.insert(Target::HighPriority, AtomicU32::new(5000)); // 20 sats per byte
let client = Self {
bitcoind_rpc_client: Arc::new(bitcoind_rpc_client),
fees: Arc::new(fees),
handle: handle.clone(),
};
BitcoindClient::poll_for_fee_estimates(
client.fees.clone(),
client.bitcoind_rpc_client.clone(),
handle,
);
Ok(client)
}
fn poll_for_fee_estimates(
fees: Arc<HashMap<Target, AtomicU32>>,
rpc_client: Arc<RpcClient>,
handle: tokio::runtime::Handle,
) {
handle.spawn(async move {
loop {
let background_estimate = {
let background_conf_target = serde_json::json!(144);
let background_estimate_mode = serde_json::json!("ECONOMICAL");
let resp = rpc_client
.call_method::<FeeResponse>(
"estimatesmartfee",
&[background_conf_target, background_estimate_mode],
)
.await
.unwrap();
match resp.feerate_sat_per_kw {
Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
None => MIN_FEERATE,
}
};
let normal_estimate = {
let normal_conf_target = serde_json::json!(18);
let normal_estimate_mode = serde_json::json!("ECONOMICAL");
let resp = rpc_client
.call_method::<FeeResponse>(
"estimatesmartfee",
&[normal_conf_target, normal_estimate_mode],
)
.await
.unwrap();
match resp.feerate_sat_per_kw {
Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
None => 2000,
}
};
let high_prio_estimate = {
let high_prio_conf_target = serde_json::json!(6);
let high_prio_estimate_mode = serde_json::json!("CONSERVATIVE");
let resp = rpc_client
.call_method::<FeeResponse>(
"estimatesmartfee",
&[high_prio_conf_target, high_prio_estimate_mode],
)
.await
.unwrap();
match resp.feerate_sat_per_kw {
Some(feerate) => std::cmp::max(feerate, MIN_FEERATE),
None => 5000,
}
};
fees.get(&Target::Background)
.unwrap()
.store(background_estimate, Ordering::Release);
fees.get(&Target::Normal)
.unwrap()
.store(normal_estimate, Ordering::Release);
fees.get(&Target::HighPriority)
.unwrap()
.store(high_prio_estimate, Ordering::Release);
tokio::time::sleep(Duration::from_secs(60)).await;
}
});
}
}
impl FeeEstimator for BitcoindClient {
fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32 {
match confirmation_target {
ConfirmationTarget::Background => self
.fees
.get(&Target::Background)
.unwrap()
.load(Ordering::Acquire),
ConfirmationTarget::Normal => self
.fees
.get(&Target::Normal)
.unwrap()
.load(Ordering::Acquire),
ConfirmationTarget::HighPriority => self
.fees
.get(&Target::HighPriority)
.unwrap()
.load(Ordering::Acquire),
}
}
}
impl BroadcasterInterface for BitcoindClient {
fn broadcast_transaction(&self, tx: &Transaction) {
let bitcoind_rpc_client = self.bitcoind_rpc_client.clone();
let tx_serialized = serde_json::json!(encode::serialize_hex(tx));
self.handle.spawn(async move {
// This may error due to RL calling `broadcast_transaction` with the same transaction
// multiple times, but the error is safe to ignore.
match bitcoind_rpc_client
.call_method::<Txid>("sendrawtransaction", &[tx_serialized])
.await
{
Ok(_) => {}
Err(e) => {
let err_str = e.get_ref().unwrap().to_string();
if !err_str.contains("Transaction already in block chain")
&& !err_str.contains("Inputs missing or spent")
&& !err_str.contains("bad-txns-inputs-missingorspent")
&& !err_str.contains("non-BIP68-final")
&& !err_str.contains("insufficient fee, rejecting replacement ")
{
panic!("{}", e);
}
}
}
});
}
}
|
use std::io::{self, Write};
use std::fs::{remove_file, remove_dir};
use std::path::Path;
use std::fmt;
use std::process;
const FILE_NAME: &'static str = "output.txt";
const DIR_NAME: &'static str = "demos";
fn main() {
}
fn delete<P>(root: P) -> io::Result<()>
where P: AsRef<Path>
{
remove_file(root.as_ref().join(FILE_NAME))
.and(remove_dir(root.as_ref().join(DIR_NAME)))
}
fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! {
let _ = writeln!(&mut io::stderr(), "{:?}", error);
process::exit(code)
} |
extern crate regex;
use std::io;
use std::fs;
use std::io::BufRead;
use std::collections::HashMap;
use std::path::Path;
fn main() {
let input = parse_input();
let mut space = input.space;
for i in 1..=6 {
space = space.next_space();
println!("After {} cycles, {} cells alive", i, space.cells.len());
}
}
#[derive(PartialEq, Clone, Copy)]
enum Cell {
Alive,
}
#[derive(PartialEq)]
struct Space {
cells: HashMap<Point, Cell>,
}
type Point = (i64, i64, i64, i64);
fn neighbor_deltas() -> Vec<Point> {
(-1..=1).flat_map(|x| {
(-1..=1).flat_map(|y| {
(-1..=1).flat_map(|z| {
(-1..=1).map(|w| {
if x == 0 && y == 0 && z == 0 && w == 0 {
None
} else {
Some((x, y, z, w))
}
}).filter_map(|maybe| maybe).collect::<Vec<_>>()
}).collect::<Vec<_>>()
}).collect::<Vec<_>>()
}).collect::<Vec<_>>()
}
impl Space {
fn next_space(&self) -> Space {
let min_x = self.cells.keys().map(|(x, _, _, _)| x).min().unwrap() - 1;
let min_y = self.cells.keys().map(|(_, y, _, _)| y).min().unwrap() - 1;
let min_z = self.cells.keys().map(|(_, _, z, _)| z).min().unwrap() - 1;
let min_w = self.cells.keys().map(|(_, _, _, w)| w).min().unwrap() - 1;
let max_x = self.cells.keys().map(|(x, _, _, _)| x).max().unwrap() + 1;
let max_y = self.cells.keys().map(|(_, y, _, _)| y).max().unwrap() + 1;
let max_z = self.cells.keys().map(|(_, _, z, _)| z).max().unwrap() + 1;
let max_w = self.cells.keys().map(|(_, _, _, w)| w).max().unwrap() + 1;
let points: Vec<Point> = (min_x..=max_x).flat_map(|x| {
(min_y..=max_y).flat_map(|y| {
(min_w..=max_w).flat_map(|w| {
(min_z..=max_z).map(|z| (x, y, z, w)).collect::<Vec<Point>>()
}).collect::<Vec<Point>>()
}).collect::<Vec<Point>>()
}).collect();
Space {
cells: points.iter().filter(|p| {
match (self.cells.get(p), self.occupied_neighbors(p)) {
(Some(Cell::Alive), 2..=3) => true,
(None, 3) => true,
_ => false
}
}).map(|p| (*p, Cell::Alive)).collect(),
}
}
fn occupied_neighbors(&self, point: &Point) -> usize {
let (x, y, z, w) = point;
neighbor_deltas().iter().map(|(dx, dy, dz, dw)| {
let new_point = (x + dx, y + dy, z + dz, w + dw);
match self.cells.get(&new_point) {
Some(Cell::Alive) => 1,
_ => 0,
}
}).sum()
}
}
struct InputData {
space: Space,
}
fn parse_input() -> InputData {
let io_result = lines_in_file("inputs/day17.txt");
match io_result {
Ok(lines) => {
let cells = lines.enumerate().flat_map(|(i, line)| match line {
Ok(stuff) => {
stuff.
chars().
enumerate().
filter(|(_, c)| *c == '#').
map(|(j, _)| ((i as i64, j as i64, 0, 0), Cell::Alive)).
collect::<Vec<_>>()
}
Err(_) => panic!("Error reading line"),
}).collect();
InputData {
space: Space { cells: cells },
}
},
Err(_) => panic!("Error reading file"),
}
}
fn lines_in_file<P>(file_path: P) -> io::Result<io::Lines<io::BufReader<fs::File>>> where P: AsRef<Path> {
let file = fs::File::open(file_path)?;
Ok(io::BufReader::new(file).lines())
}
|
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Claims {
pub user_id: String,
pub iat: i64,
pub exp: i64,
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.