text stringlengths 8 4.13M |
|---|
fn main() {
let reference_to_nothing = dangle();
}
fn dangle () -> &String {
let s = String::from ("hello");
&s
} //here s goes out of scope so does the refernce to that memory too, hence the returning address "&String" is not pointing to string "s";
|
fn read<T: std::str::FromStr>() -> T {
let mut s = String::new();
std::io::stdin().read_line(&mut s).ok();
s.trim().parse().ok().unwrap()
}
fn main() {
let s: String = read();
let cv: Vec<char> = s.chars().collect();
if cv[0] != cv[1] {
if (cv[0] == cv[2] && cv[1] == cv[3]) || (cv[0] == cv[3] && cv[1] == cv[2]) {
println!("Yes");
} else {
println!("No");
}
} else {
if cv[1] != cv[2] && cv[2] == cv[3] {
println!("Yes");
} else {
println!("No");
}
}
}
|
#[doc = "Register `ETH_MACISR` reader"]
pub type R = crate::R<ETH_MACISR_SPEC>;
#[doc = "Field `RGSMIIIS` reader - RGSMIIIS"]
pub type RGSMIIIS_R = crate::BitReader;
#[doc = "Field `PHYIS` reader - PHYIS"]
pub type PHYIS_R = crate::BitReader;
#[doc = "Field `PMTIS` reader - PMTIS"]
pub type PMTIS_R = crate::BitReader;
#[doc = "Field `LPIIS` reader - LPIIS"]
pub type LPIIS_R = crate::BitReader;
#[doc = "Field `MMCIS` reader - MMCIS"]
pub type MMCIS_R = crate::BitReader;
#[doc = "Field `MMCRXIS` reader - MMCRXIS"]
pub type MMCRXIS_R = crate::BitReader;
#[doc = "Field `MMCTXIS` reader - MMCTXIS"]
pub type MMCTXIS_R = crate::BitReader;
#[doc = "Field `TSIS` reader - TSIS"]
pub type TSIS_R = crate::BitReader;
#[doc = "Field `TXSTSIS` reader - TXSTSIS"]
pub type TXSTSIS_R = crate::BitReader;
#[doc = "Field `RXSTSIS` reader - RXSTSIS"]
pub type RXSTSIS_R = crate::BitReader;
impl R {
#[doc = "Bit 0 - RGSMIIIS"]
#[inline(always)]
pub fn rgsmiiis(&self) -> RGSMIIIS_R {
RGSMIIIS_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 3 - PHYIS"]
#[inline(always)]
pub fn phyis(&self) -> PHYIS_R {
PHYIS_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - PMTIS"]
#[inline(always)]
pub fn pmtis(&self) -> PMTIS_R {
PMTIS_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - LPIIS"]
#[inline(always)]
pub fn lpiis(&self) -> LPIIS_R {
LPIIS_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 8 - MMCIS"]
#[inline(always)]
pub fn mmcis(&self) -> MMCIS_R {
MMCIS_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - MMCRXIS"]
#[inline(always)]
pub fn mmcrxis(&self) -> MMCRXIS_R {
MMCRXIS_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - MMCTXIS"]
#[inline(always)]
pub fn mmctxis(&self) -> MMCTXIS_R {
MMCTXIS_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 12 - TSIS"]
#[inline(always)]
pub fn tsis(&self) -> TSIS_R {
TSIS_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - TXSTSIS"]
#[inline(always)]
pub fn txstsis(&self) -> TXSTSIS_R {
TXSTSIS_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - RXSTSIS"]
#[inline(always)]
pub fn rxstsis(&self) -> RXSTSIS_R {
RXSTSIS_R::new(((self.bits >> 14) & 1) != 0)
}
}
#[doc = "The Interrupt Status register contains the status of interrupts.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eth_macisr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct ETH_MACISR_SPEC;
impl crate::RegisterSpec for ETH_MACISR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`eth_macisr::R`](R) reader structure"]
impl crate::Readable for ETH_MACISR_SPEC {}
#[doc = "`reset()` method sets ETH_MACISR to value 0"]
impl crate::Resettable for ETH_MACISR_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::collections::{HashMap, HashSet};
use std::ops::{Add, AddAssign};
use crate::{BreakingInfo, Change, ChangeType, SemverScope};
#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct ChangeLog {
breaking_changes: Section,
features: Section,
fixes: Section,
scopes: HashSet<Option<Scope>>,
}
pub(crate) type Scope = String;
pub(crate) type Section = HashMap<Option<Scope>, Vec<String>>;
impl AddAssign<Change<'_>> for ChangeLog {
fn add_assign(&mut self, change: Change<'_>) {
let scope = change.scope.map(String::from);
match change.breaking {
BreakingInfo::NotBreaking => (),
BreakingInfo::Breaking => Self::append(
&mut self.scopes,
&mut self.breaking_changes,
scope.clone(),
change.description,
),
BreakingInfo::BreakingWithDescriptions(descriptions) => {
for desc in descriptions {
Self::append(
&mut self.scopes,
&mut self.breaking_changes,
scope.clone(),
desc,
);
}
}
}
let section = match change.type_ {
ChangeType::Fix => &mut self.fixes,
ChangeType::Feature => &mut self.features,
ChangeType::Custom(_) => return,
};
Self::append(&mut self.scopes, section, scope, change.description);
}
}
impl Add<Change<'_>> for ChangeLog {
type Output = Self;
#[inline]
fn add(mut self, rhs: Change<'_>) -> Self::Output {
self += rhs;
self
}
}
impl ChangeLog {
pub fn has_feature_or_fix(&self) -> bool {
!self.features.is_empty() || !self.fixes.is_empty()
}
pub fn semver_scope(&self) -> Option<SemverScope> {
if !self.breaking_changes.is_empty() {
Some(SemverScope::Breaking)
} else if !self.features.is_empty() {
Some(SemverScope::Feature)
} else if !self.fixes.is_empty() {
Some(SemverScope::Fix)
} else {
None
}
}
pub(crate) fn scopes(&self) -> impl Iterator<Item = &Option<Scope>> {
self.scopes.iter()
}
pub(crate) fn breaking_changes(&self) -> &Section {
&self.breaking_changes
}
pub(crate) fn features(&self) -> &Section {
&self.features
}
pub(crate) fn fixes(&self) -> &Section {
&self.fixes
}
fn append(
scopes: &mut HashSet<Option<Scope>>,
section: &mut Section,
scope: Option<Scope>,
value: &str,
) {
if !scopes.contains(&scope) {
scopes.insert(scope.clone());
}
section.entry(scope).or_default().push(value.to_owned());
}
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use super::*;
#[test]
pub fn is_empty_by_default() {
let default = ChangeLog::default();
assert!(default.semver_scope().is_none());
assert!(default.breaking_changes().is_empty());
assert!(default.features().is_empty());
assert!(default.fixes().is_empty());
assert!(default.scopes().collect::<Vec<_>>().is_empty());
}
#[test]
pub fn adding_non_breaking_custom_type_change_has_no_effect() {
let changelog = ChangeLog::default() + Change::new(ChangeType::Custom("testing"), "...");
assert!(changelog.semver_scope().is_none());
assert_eq!(ChangeLog::default(), changelog);
}
#[rstest]
#[case(None)]
#[case(Some("main"))]
#[case(Some("changelog"))]
pub fn stores_features(#[case] scope: Option<&str>) {
let change1 = Change {
scope,
..Change::new(ChangeType::Feature, "Hello world!")
};
let change2 = Change {
scope,
..Change::new(ChangeType::Feature, "Goodbye world!")
};
let changelog = ChangeLog::default() + change1.clone() + change2.clone();
assert_eq!(
changelog.scopes().cloned().collect::<Vec<_>>(),
vec![scope.map(String::from)]
);
assert_eq!(changelog.semver_scope(), Some(SemverScope::Feature));
assert_eq!(
changelog
.features()
.get(&scope.map(String::from))
.expect("Entry not added"),
&vec![change1.description, change2.description],
);
}
#[rstest]
#[case(None)]
#[case(Some("main"))]
#[case(Some("changelog"))]
pub fn stores_fixes(#[case] scope: Option<&str>) {
let mut change1 = Change::new(ChangeType::Fix, "Hello world!");
change1.scope = scope;
let mut change2 = Change::new(ChangeType::Fix, "Goodbye world!");
change2.scope = scope;
let changelog = ChangeLog::default() + change1.clone() + change2.clone();
assert_eq!(
changelog.scopes().cloned().collect::<Vec<_>>(),
vec![scope.map(String::from)]
);
assert_eq!(changelog.semver_scope(), Some(SemverScope::Fix));
assert_eq!(
changelog
.fixes()
.get(&scope.map(String::from))
.expect("Entry not added"),
&vec![change1.description, change2.description],
);
}
#[rstest]
#[case(ChangeType::Feature)]
#[case(ChangeType::Fix)]
#[case(ChangeType::Custom("test"))]
fn appends_description_to_breaking_changes_if_there_is_no_more_info(#[case] type_: ChangeType) {
let description = "Hello world!";
let mut change = Change::new(type_, description);
change.breaking = BreakingInfo::Breaking;
let changelog = ChangeLog::default() + change;
assert_eq!(changelog.semver_scope(), Some(SemverScope::Breaking));
assert_eq!(
changelog
.breaking_changes
.get(&None)
.expect("Entry not added"),
&vec![String::from(description)],
);
}
#[rstest]
#[case(ChangeType::Feature)]
#[case(ChangeType::Fix)]
#[case(ChangeType::Custom("test"))]
fn breaking_changes_info_are_appended_to_breaking_changes(#[case] type_: ChangeType) {
let description = "Hello world!";
let mut change = Change::new(type_, description);
change.breaking = BreakingInfo::BreakingWithDescriptions(vec!["one", "two"]);
let changelog = ChangeLog::default() + change;
assert_eq!(changelog.semver_scope(), Some(SemverScope::Breaking));
assert_eq!(
changelog
.breaking_changes
.get(&None)
.expect("Entry not added"),
&vec![String::from("one"), String::from("two")],
);
}
}
|
use std::collections::HashMap;
use timely::dataflow::channels::pact::Exchange;
use timely::dataflow::operators::{Inspect, Map, Operator, Probe};
use timely::dataflow::{InputHandle, ProbeHandle};
use std::io::{self, Read};
use std::fs::File;
use std::hash::Hash;
use word_count::util::*;
fn hash_str(text: &str) -> u64 {
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
let mut hasher = DefaultHasher::new();
text.hash(&mut hasher);
hasher.finish()
}
fn main() {
// initializes and runs a timely dataflow.
timely::execute(timely::Configuration::Process(4), |worker| {
let mut input = InputHandle::new();
let mut probe = ProbeHandle::new();
// define a distribution function for strings.
//let exchange = Exchange::new(|x: &(String, i64)| hash_str(&x.0));
let exchange = Exchange::new(|x: &(String, i64)| x.0.len() as u64);
// create a new input, exchange data, and inspect its output
worker.dataflow::<usize, _, _>(|scope| {
input
.to_stream(scope)
.flat_map(|(text, diff): (String, i64)| {
text.split_whitespace()
.map(move |word| (word.to_owned(), diff))
.collect::<Vec<_>>()
})
.unary_frontier(exchange, "WordCount", |_capability, _info| {
let mut queues = HashMap::new();
let mut counts = HashMap::new();
move |input, output| {
while let Some((time, data)) = input.next() {
queues
.entry(time.retain())
.or_insert(Vec::new())
.push(data.replace(Vec::new()));
}
for (key, val) in queues.iter_mut() {
if !input.frontier().less_equal(key.time()) {
let mut session = output.session(key);
for mut batch in val.drain(..) {
for (word, diff) in batch.drain(..) {
let entry = counts.entry(word.clone()).or_insert(0i64);
*entry += diff;
session.give((word, *entry));
}
}
}
}
queues.retain(|_key, val| !val.is_empty());
}
})
.inspect_time(|time, x| {
if time % 1000 == 0 {
println!("{}k: {:?}", time / 1000, x)
}
})
.probe_with(&mut probe);
});
if worker.index() == 0 {
let conf = parse_args("word count dataflow");
let mut buffer = String::new();
if let Some(filename) = conf.input {
File::open(&filename)
.expect(format!("can't open file \"{}\"", &filename).as_str())
.read_to_string(&mut buffer)
.expect(format!("can't read file \"{}\"", &filename).as_str());
} else {
io::stdin()
.read_to_string(&mut buffer)
.expect("can't read stdin");
}
let mut round: usize = 0;
for word in buffer.split_ascii_whitespace() {
input.send((word.to_owned(), 1));
round = round + 1;
input.advance_to(round);
while probe.less_than(input.time()) {
worker.step();
}
}
input.close();
}
/*
// introduce data and watch!
for round in 0..10 {
input.send(("round".to_owned(), 1));
input.advance_to(round + 1);
while probe.less_than(input.time()) {
worker.step();
}
}
*/
})
.unwrap();
}
|
// adapted from https://www.softax.pl/blog/rust-lang-in-a-nutshell-3-traits-and-generics/
use benchmarking;
use std::env;
use std::process;
struct Fibonacci(u32, u128, u128);
impl Fibonacci {
fn new() -> Fibonacci {
Fibonacci(0, 0, 1)
}
}
trait Limit {
// u128 can't hold Fibonacci sequence numbers higher than this position
const LIMIT: u32 = 185;
}
impl Limit for Fibonacci {}
impl Iterator for Fibonacci {
type Item = u128;
fn next(&mut self) -> Option<u128> {
self.0 += 1;
if self.0 > Self::LIMIT {
return None;
}
let new_next: u128 = self.1 + self.2;
self.1 = self.2;
self.2 = new_next;
Some(self.1)
}
}
/*
trait Next {
fn next(&mut self) -> Option<u128>;
}
impl Next for Fibonacci {
fn next(&mut self) -> Option<u128> { Some(0) }
}
*/
const BENCHMARK_ITERATIONS: u64 = 1_000_000;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
eprintln!("Please supply one argument, the Fibonacci sequence number to go to");
process::exit(1);
}
let num = args[1].parse().unwrap();
benchmarking::warm_up();
let bench_result =
benchmarking::measure_function_with_times(BENCHMARK_ITERATIONS, move |measurer| {
measurer.measure(|| {
let seq = Fibonacci::new();
// Skip printing for the benchmark, to just measure non-I/O time
seq.take(num).last();
/*
let mut i: u32 = 0;
for i in seq.take(num) {
i += 1;
println!("{}: {}", i, n);
}
*/
});
})
.unwrap();
println!(
"Grabbing those Fibonacci numbers takes {:?}",
bench_result.elapsed()
);
}
|
use std::borrow::Cow;
use std::cmp::{max, min};
use std::env;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::Arc;
use std::thread;
use std::thread::JoinHandle;
use derive_builder::Builder;
use nix::libc;
use regex::Regex;
use tuikit::prelude::{Event as TermEvent, *};
use crate::ansi::{ANSIParser, AnsiString};
use crate::event::{Event, EventHandler, UpdateScreen};
use crate::spinlock::SpinLock;
use crate::util::{atoi, clear_canvas, depends_on_items, inject_command, InjectContext};
use crate::{ItemPreview, PreviewContext, PreviewPosition, SkimItem};
const TAB_STOP: usize = 8;
const DELIMITER_STR: &str = r"[\t\n ]+";
pub struct Previewer {
tx_preview: Sender<PreviewEvent>,
content_lines: Arc<SpinLock<Vec<AnsiString<'static>>>>,
width: Arc<AtomicUsize>,
height: Arc<AtomicUsize>,
hscroll_offset: Arc<AtomicUsize>,
vscroll_offset: Arc<AtomicUsize>,
wrap: bool,
prev_item: Option<Arc<dyn SkimItem>>,
prev_query: Option<String>,
prev_cmd_query: Option<String>,
prev_num_selected: usize,
preview_cmd: Option<String>,
preview_offset: String, // e.g. +SCROLL-OFFSET
delimiter: Regex,
thread_previewer: Option<JoinHandle<()>>,
}
impl Previewer {
pub fn new<C>(preview_cmd: Option<String>, callback: C) -> Self
where
C: Fn() + Send + Sync + 'static,
{
let content_lines = Arc::new(SpinLock::new(Vec::new()));
let (tx_preview, rx_preview) = channel();
let width = Arc::new(AtomicUsize::new(80));
let height = Arc::new(AtomicUsize::new(60));
let hscroll_offset = Arc::new(AtomicUsize::new(1));
let vscroll_offset = Arc::new(AtomicUsize::new(1));
let content_clone = content_lines.clone();
let width_clone = width.clone();
let height_clone = height.clone();
let hscroll_offset_clone = hscroll_offset.clone();
let vscroll_offset_clone = vscroll_offset.clone();
let thread_previewer = thread::spawn(move || {
run(rx_preview, move |lines, pos| {
let width = width_clone.load(Ordering::SeqCst);
let height = height_clone.load(Ordering::SeqCst);
let hscroll = pos.h_scroll.calc_fixed_size(lines.len(), 0);
let hoffset = pos.h_offset.calc_fixed_size(width, 0);
let vscroll = pos.v_scroll.calc_fixed_size(usize::MAX, 0);
let voffset = pos.v_offset.calc_fixed_size(height, 0);
hscroll_offset_clone.store(max(1, max(hscroll, hoffset) - hoffset), Ordering::SeqCst);
vscroll_offset_clone.store(max(1, max(vscroll, voffset) - voffset), Ordering::SeqCst);
*content_clone.lock() = lines;
callback();
})
});
Self {
tx_preview,
content_lines,
width,
height,
hscroll_offset,
vscroll_offset,
wrap: false,
prev_item: None,
prev_query: None,
prev_cmd_query: None,
prev_num_selected: 0,
preview_cmd,
preview_offset: "".to_string(),
delimiter: Regex::new(DELIMITER_STR).unwrap(),
thread_previewer: Some(thread_previewer),
}
}
pub fn wrap(mut self, wrap: bool) -> Self {
self.wrap = wrap;
self
}
pub fn delimiter(mut self, delimiter: Regex) -> Self {
self.delimiter = delimiter;
self
}
// e.g. +SCROLL-OFFSET
pub fn preview_offset(mut self, offset: String) -> Self {
self.preview_offset = offset;
self
}
#[allow(clippy::too_many_arguments)]
pub fn on_item_change(
&mut self,
new_item_index: usize,
new_item: impl Into<Option<Arc<dyn SkimItem>>>,
new_query: impl Into<Option<String>>,
new_cmd_query: impl Into<Option<String>>,
num_selected: usize,
get_selected_items: impl Fn() -> (Vec<usize>, Vec<Arc<dyn SkimItem>>), // lazy get
force: bool,
) {
let new_item = new_item.into();
let new_query = new_query.into();
let new_cmd_query = new_cmd_query.into();
let item_changed = match (self.prev_item.as_ref(), new_item.as_ref()) {
(None, None) => false,
(None, Some(_)) => true,
(Some(_), None) => true,
#[allow(clippy::vtable_address_comparisons)]
(Some(prev), Some(new)) => !Arc::ptr_eq(prev, new),
};
let query_changed = match (self.prev_query.as_ref(), new_query.as_ref()) {
(None, None) => false,
(None, Some(_)) => true,
(Some(_), None) => true,
(Some(prev), Some(cur)) => prev != cur,
};
let cmd_query_changed = match (self.prev_cmd_query.as_ref(), new_cmd_query.as_ref()) {
(None, None) => false,
(None, Some(_)) => true,
(Some(_), None) => true,
(Some(prev), Some(cur)) => prev != cur,
};
let selected_items_changed = self.prev_num_selected != num_selected;
if !force && !item_changed && !query_changed && !cmd_query_changed && !selected_items_changed {
return;
}
self.prev_item = new_item.clone();
self.prev_query = new_query;
self.prev_cmd_query = new_cmd_query;
self.prev_num_selected = num_selected;
// prepare preview context
let current_selection = self
.prev_item
.as_ref()
.map(|item| item.output())
.unwrap_or_else(|| "".into());
let query = self.prev_query.as_deref().unwrap_or("");
let cmd_query = self.prev_cmd_query.as_deref().unwrap_or("");
let (indices, selections) = get_selected_items();
let tmp: Vec<Cow<str>> = selections.iter().map(|item| item.text()).collect();
let selected_texts: Vec<&str> = tmp.iter().map(|cow| cow.as_ref()).collect();
let columns = self.width.load(Ordering::Relaxed);
let lines = self.height.load(Ordering::Relaxed);
let inject_context = InjectContext {
current_index: new_item_index,
delimiter: &self.delimiter,
current_selection: ¤t_selection,
selections: &selected_texts,
indices: &indices,
query,
cmd_query,
};
let preview_context = PreviewContext {
query,
cmd_query,
width: columns,
height: lines,
current_index: new_item_index,
current_selection: ¤t_selection,
selected_indices: &indices,
selections: &selected_texts,
};
let preview_event = match new_item {
Some(item) => match (item.preview(preview_context), PreviewPosition::default()) {
(ItemPreview::Text(text), pos) => PreviewEvent::PreviewPlainText(text, pos),
(ItemPreview::AnsiText(text), pos) => PreviewEvent::PreviewAnsiText(text, pos),
(ItemPreview::TextWithPos(text, pos), _) => PreviewEvent::PreviewPlainText(text, pos),
(ItemPreview::AnsiWithPos(text, pos), _) => PreviewEvent::PreviewAnsiText(text, pos),
(ItemPreview::Command(cmd), pos) | (ItemPreview::CommandWithPos(cmd, pos), _) => {
if depends_on_items(&cmd) && self.prev_item.is_none() {
debug!("the command for preview refers to items and currently there is no item");
debug!("command to execute: [{}]", cmd);
PreviewEvent::PreviewPlainText("no item matched".to_string(), Default::default())
} else {
let cmd = inject_command(&cmd, inject_context).to_string();
let preview_command = PreviewCommand { cmd, columns, lines };
PreviewEvent::PreviewCommand(preview_command, pos)
}
}
(ItemPreview::Global, _) => {
let cmd = self.preview_cmd.clone().expect("previewer: not provided");
if depends_on_items(&cmd) && self.prev_item.is_none() {
debug!("the command for preview refers to items and currently there is no item");
debug!("command to execute: [{}]", cmd);
PreviewEvent::PreviewPlainText("no item matched".to_string(), Default::default())
} else {
let cmd = inject_command(&cmd, inject_context).to_string();
let pos = self.eval_scroll_offset(inject_context);
let preview_command = PreviewCommand { cmd, columns, lines };
PreviewEvent::PreviewCommand(preview_command, pos)
}
}
},
None => PreviewEvent::Noop,
};
let _ = self.tx_preview.send(preview_event);
}
fn act_scroll_down(&mut self, diff: i32) {
let vscroll_offset = self.vscroll_offset.load(Ordering::SeqCst);
let new_offset = if diff > 0 {
vscroll_offset + diff as usize
} else {
vscroll_offset - min((-diff) as usize, vscroll_offset)
};
let new_offset = min(new_offset, max(self.content_lines.lock().len(), 1) - 1);
self.vscroll_offset.store(max(new_offset, 1), Ordering::SeqCst);
}
fn act_scroll_right(&mut self, diff: i32) {
let hscroll_offset = self.hscroll_offset.load(Ordering::SeqCst);
let new_offset = if diff > 0 {
hscroll_offset + diff as usize
} else {
hscroll_offset - min((-diff) as usize, hscroll_offset)
};
self.hscroll_offset.store(max(1, new_offset), Ordering::SeqCst);
}
fn act_toggle_wrap(&mut self) {
self.wrap = !self.wrap;
}
fn eval_scroll_offset(&self, context: InjectContext) -> PreviewPosition {
// currently, only h_scroll and h_offset is supported
// The syntax follows fzf's
// +SCROLL[-OFFSET] determines the initial scroll offset of the preview window.
// SCROLL can be either a numeric integer or a single-field index expression
// that refers to a numeric integer. The optional -OFFSET part is for adjusting
// the base offset so that you can see the text above it. It should be given as a
// numeric integer (-INTEGER), or as a denominator form (-/INTEGER) for
// specifying a fraction of the preview window height
if self.preview_offset.is_empty() {
return Default::default();
}
let offset_expr = inject_command(&self.preview_offset, context);
if offset_expr.is_empty() {
return Default::default();
}
let nums: Vec<&str> = offset_expr.split('-').collect();
let v_scroll = if nums.is_empty() {
Size::Default
} else {
Size::Fixed(atoi::<usize>(nums[0]).unwrap_or(0))
};
let v_offset = if nums.len() >= 2 {
let expr = nums[1];
if expr.starts_with('/') {
let num = atoi::<usize>(expr).unwrap_or(0);
Size::Percent(if num == 0 { 0 } else { 100 / num })
} else {
let num = atoi::<usize>(expr).unwrap_or(0);
Size::Fixed(num)
}
} else {
Size::Default
};
PreviewPosition {
h_scroll: Default::default(),
h_offset: Default::default(),
v_scroll,
v_offset,
}
}
}
impl Drop for Previewer {
fn drop(&mut self) {
let _ = self.tx_preview.send(PreviewEvent::Abort);
self.thread_previewer.take().map(|handle| handle.join());
}
}
impl EventHandler for Previewer {
fn handle(&mut self, event: &Event) -> UpdateScreen {
use crate::event::Event::*;
let height = self.height.load(Ordering::Relaxed);
match event {
EvActTogglePreviewWrap => self.act_toggle_wrap(),
EvActPreviewUp(diff) => self.act_scroll_down(-*diff),
EvActPreviewDown(diff) => self.act_scroll_down(*diff),
EvActPreviewLeft(diff) => self.act_scroll_right(-*diff),
EvActPreviewRight(diff) => self.act_scroll_right(*diff),
EvActPreviewPageUp(diff) => self.act_scroll_down(-(height as i32 * *diff)),
EvActPreviewPageDown(diff) => self.act_scroll_down(height as i32 * *diff),
_ => return UpdateScreen::DONT_REDRAW,
}
UpdateScreen::REDRAW
}
}
impl Draw for Previewer {
fn draw(&self, canvas: &mut dyn Canvas) -> DrawResult<()> {
canvas.clear()?;
let (screen_width, screen_height) = canvas.size()?;
clear_canvas(canvas)?;
if screen_width == 0 || screen_height == 0 {
return Ok(());
}
self.width.store(screen_width, Ordering::Relaxed);
self.height.store(screen_height, Ordering::Relaxed);
let content = self.content_lines.lock();
let vscroll_offset = self.vscroll_offset.load(Ordering::SeqCst);
let hscroll_offset = self.hscroll_offset.load(Ordering::SeqCst);
let mut printer = PrinterBuilder::default()
.width(screen_width)
.height(screen_height)
.skip_rows(max(1, vscroll_offset) - 1)
.skip_cols(max(1, hscroll_offset) - 1)
.wrap(self.wrap)
.build()
.unwrap();
printer.print_lines(canvas, &content);
// print the vscroll info
let status = format!("{}/{}", vscroll_offset, content.len());
let col = max(status.len() + 1, screen_width - status.len() - 1);
canvas.print_with_attr(
0,
col,
&status,
Attr {
effect: Effect::REVERSE,
..Attr::default()
},
)?;
Ok(())
}
}
impl Widget<Event> for Previewer {
fn on_event(&self, event: TermEvent, _rect: Rectangle) -> Vec<Event> {
let mut ret = vec![];
match event {
TermEvent::Key(Key::WheelUp(.., count)) => ret.push(Event::EvActPreviewUp(count as i32)),
TermEvent::Key(Key::WheelDown(.., count)) => ret.push(Event::EvActPreviewDown(count as i32)),
_ => {}
}
ret
}
}
#[derive(Debug, Ord, PartialOrd, PartialEq, Eq)]
pub struct PreviewCommand {
pub cmd: String,
pub lines: usize,
pub columns: usize,
}
#[derive(Debug)]
enum PreviewEvent {
PreviewCommand(PreviewCommand, PreviewPosition),
PreviewPlainText(String, PreviewPosition),
PreviewAnsiText(String, PreviewPosition),
Noop,
Abort,
}
struct PreviewThread {
pid: u32,
thread: thread::JoinHandle<()>,
stopped: Arc<AtomicBool>,
}
impl PreviewThread {
fn kill(self) {
if !self.stopped.load(Ordering::Relaxed) {
unsafe { libc::kill(self.pid as i32, libc::SIGKILL) };
}
self.thread.join().expect("Failed to join Preview process");
}
}
fn run<C>(rx_preview: Receiver<PreviewEvent>, on_return: C)
where
C: Fn(Vec<AnsiString<'static>>, PreviewPosition) + Send + Sync + 'static,
{
let callback = Arc::new(on_return);
let mut preview_thread: Option<PreviewThread> = None;
while let Ok(_event) = rx_preview.recv() {
if preview_thread.is_some() {
preview_thread.unwrap().kill();
preview_thread = None;
}
let mut event = match _event {
PreviewEvent::Abort => return,
_ => _event,
};
// Try to empty the channel. Happens when spamming up/down or typing fast.
while let Ok(_event) = rx_preview.try_recv() {
event = match _event {
PreviewEvent::Abort => return,
_ => _event,
}
}
match event {
PreviewEvent::PreviewCommand(preview_cmd, pos) => {
let cmd = &preview_cmd.cmd;
if cmd.is_empty() {
continue;
}
let shell = env::var("SHELL").unwrap_or_else(|_| "sh".to_string());
let spawned = Command::new(shell)
.env("LINES", preview_cmd.lines.to_string())
.env("COLUMNS", preview_cmd.columns.to_string())
.arg("-c")
.arg(&cmd)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn();
match spawned {
Err(err) => {
let astdout = AnsiString::parse(format!("Failed to spawn: {} / {}", cmd, err).as_str());
callback(vec![astdout], pos);
preview_thread = None;
}
Ok(spawned) => {
let pid = spawned.id();
let stopped = Arc::new(AtomicBool::new(false));
let stopped_clone = stopped.clone();
let callback_clone = callback.clone();
let thread = thread::spawn(move || {
wait(spawned, move |lines| {
stopped_clone.store(true, Ordering::SeqCst);
callback_clone(lines, pos);
})
});
preview_thread = Some(PreviewThread { pid, thread, stopped });
}
}
}
PreviewEvent::PreviewPlainText(text, pos) => {
callback(text.lines().map(|line| line.to_string().into()).collect(), pos);
}
PreviewEvent::PreviewAnsiText(text, pos) => {
let mut parser = ANSIParser::default();
let color_lines = text.lines().map(|line| parser.parse_ansi(line)).collect();
callback(color_lines, pos);
}
PreviewEvent::Noop => {}
PreviewEvent::Abort => return,
};
}
}
fn wait<C>(spawned: std::process::Child, callback: C)
where
C: Fn(Vec<AnsiString<'static>>),
{
let output = spawned.wait_with_output();
if output.is_err() {
return;
}
let output = output.unwrap();
if output.status.code().is_none() {
// On Unix it means the process is terminated by a signal
// directly return to avoid flickering
return;
}
// Capture stderr in case users want to debug ...
let out_str = String::from_utf8_lossy(if output.status.success() {
&output.stdout
} else {
&output.stderr
});
let lines = out_str.lines().map(AnsiString::parse).collect();
callback(lines);
}
#[derive(Builder, Default, Debug)]
#[builder(default)]
struct Printer {
#[builder(setter(skip))]
row: usize,
#[builder(setter(skip))]
col: usize,
skip_rows: usize,
skip_cols: usize,
wrap: bool,
width: usize,
height: usize,
}
impl Printer {
pub fn print_lines(&mut self, canvas: &mut dyn Canvas, content: &[AnsiString]) {
for (line_no, line) in content.iter().enumerate() {
if line_no < self.skip_rows {
self.move_to_next_line();
continue;
} else if self.row >= self.skip_rows + self.height {
break;
}
for (ch, attr) in line.iter() {
let _ = self.print_char_with_attr(canvas, ch, attr);
// skip if the content already exceeded the canvas
if !self.wrap && self.col >= self.width + self.skip_cols {
break;
}
if self.row >= self.skip_rows + self.height {
break;
}
}
self.move_to_next_line();
}
}
fn move_to_next_line(&mut self) {
self.row += 1;
self.col = 0;
}
fn print_char_with_attr(&mut self, canvas: &mut dyn Canvas, ch: char, attr: Attr) -> Result<()> {
match ch {
'\n' | '\r' | '\0' => {}
'\t' => {
// handle tabstop
let rest = TAB_STOP - self.col % TAB_STOP;
let rest = min(rest, max(self.col, self.width) - self.col);
for _ in 0..rest {
self.print_char_raw(canvas, ' ', attr)?;
}
}
ch => {
self.print_char_raw(canvas, ch, attr)?;
}
}
Ok(())
}
fn print_char_raw(&mut self, canvas: &mut dyn Canvas, ch: char, attr: Attr) -> Result<()> {
if self.row < self.skip_rows || self.row >= self.height + self.skip_rows {
return Ok(());
}
if self.wrap {
// if wrap is enabled, hscroll is discarded
self.col += self.adjust_scroll_print(canvas, ch, attr)?;
if self.col >= self.width {
// re-print the wide character
self.move_to_next_line();
}
if self.col > self.width {
self.col += self.adjust_scroll_print(canvas, ch, attr)?;
}
} else {
self.col += self.adjust_scroll_print(canvas, ch, attr)?;
}
Ok(())
}
fn adjust_scroll_print(&self, canvas: &mut dyn Canvas, ch: char, attr: Attr) -> Result<usize> {
if self.row < self.skip_rows || self.col < self.skip_cols {
canvas.put_char_with_attr(usize::max_value(), usize::max_value(), ch, attr)
} else {
canvas.put_char_with_attr(self.row - self.skip_rows, self.col - self.skip_cols, ch, attr)
}
}
}
|
fn main() {
let heart_eyed_cat = '😻';
let tup = (500, 6.4, true);
let (x, y, z) = tup;
println!("The value of y is: {}", y);
println!("The first value is {}", tup.0);
another_fn(x, z);
let y = {
let x = 3;
x + 1
};
println!("The value of y is: {}", y);
let number = 17;
if number % 4 == 0 {
println!("number is divisible by 4");
} else if number % 3 == 0 {
println!("number is divisible by 3");
} else if number % 2 == 0 {
println!("number is divisible by 2");
} else {
println!("number is not divisible by 4, 3, or 2");
}
let a = [10, 20, 30, 40, 50];
let mut i=0;
for element in a.iter() {
println!("the value is: {}", element);
}
while i < a.len() {
println!("Number is {}",a[i]);
i=i+1;
}
for number in (1..5).rev() {
println!("{}!", number);
}
}
fn another_fn(x: i32, z: bool) {
println!("The value of x and z are {} and {}", x, z);
} |
/// NO. 97: Interleaving String
pub struct Solution;
// ----- submission codes start here -----
use std::collections::HashSet;
impl Solution {
pub fn is_interleave(s1: String, s2: String, s3: String) -> bool {
if s1.len() + s2.len() != s3.len() {
false
} else {
let s1 = s1.as_bytes();
let s2 = s2.as_bytes();
let s3 = s3.as_bytes();
let mut stack = vec![(0, 0)];
let mut visited = HashSet::new();
visited.insert((0, 0));
while let Some((i, j)) = stack.pop() {
if i + j == s3.len() {
return true
}
if i+1 <= s1.len() && !visited.contains(&(i+1, j)) && s1[i] == s3[i+j] {
stack.push((i+1, j));
visited.insert((i+1, j));
}
if j+1 <= s2.len() && !visited.contains(&(i, j+1)) && s2[j] == s3[i+j] {
stack.push((i, j+1));
visited.insert((i, j+1));
}
}
false
}
}
}
// ----- submission codes end here -----
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test1() {
let s1 = "aabcc".to_string();
let s2 = "dbbca".to_string();
let s3 = "aadbbcbcac".to_string();
assert_eq!(Solution::is_interleave(s1, s2, s3), true);
}
#[test]
fn test2() {
let s1 = "aabcc".to_string();
let s2 = "dbbca".to_string();
let s3 = "aadbbbaccc".to_string();
assert_eq!(Solution::is_interleave(s1, s2, s3), false);
}
#[test]
fn test3() {
let s1 = "".to_string();
let s2 = "".to_string();
let s3 = "".to_string();
assert_eq!(Solution::is_interleave(s1, s2, s3), true);
}
}
|
extern crate libc;
extern crate rand;
use libc::{c_char, c_float};
use std::cmp;
use std::f32;
use std::ffi::CStr;
use std::fmt;
use std::fs::File;
use std::io::prelude::*;
use std::mem;
use std::ops::*;
use std::ptr;
use std::slice;
use std::str::FromStr;
use rand::Rng;
// For serializing. TODO: Deprecate and replace.
extern crate rustc_serialize;
use rustc_serialize::json;
// let mut rng = rand::thread_rng();
// rng.gen() or rng.gen::<f32>() or rand::random::<(some tuple of values)>
//
// Matrix
//
#[derive(RustcDecodable, RustcEncodable)]
pub struct Matrix {
rows : usize, // Height
columns : usize, // Width
data : Vec<f32>,
}
impl Clone for Matrix {
fn clone(&self) -> Matrix {
Matrix {
rows : self.rows,
columns : self.columns,
data : self.data.clone()
}
}
}
impl Matrix {
fn new(num_rows : usize, num_cols : usize) -> Matrix {
Matrix {
rows : num_rows,
columns : num_cols,
data : vec![0.0f32; num_rows*num_cols],
}
}
fn new_from_row(d : &Vec<f32>) -> Matrix {
Matrix { rows : 1, columns : d.len(), data : d.clone() }
}
fn new_from_fn(num_rows : usize, num_cols : usize, f : Box<Fn(usize, usize)->f32>) -> Matrix {
let mut new_mat = Matrix {
rows : num_rows,
columns : num_cols,
data : vec![]
};
for i in 0..num_rows {
for j in 0..num_cols {
new_mat.data.push(f(i, j));
}
}
new_mat
}
fn new_random(num_rows : usize, num_cols : usize, scale : f32) -> Matrix {
Matrix::new_from_fn(num_rows, num_cols, Box::new(move |_,_| { rand::random::<f32>()*scale }))
}
fn get(&self, row_y : usize, col_x : usize) -> f32 {
assert!(row_y >= 0 && row_y < self.rows && col_x >= 0 && col_x < self.columns);
self.data[col_x + row_y*self.columns] // x + y*width
}
fn set(&mut self, row_y : usize, col_x : usize, value : f32) {
assert!(row_y >= 0 && row_y < self.rows && col_x >= 0 && col_x < self.columns);
self.data[col_x + row_y*self.columns] = value;
}
fn transpose(&self) -> Matrix {
let mut new_mat = Matrix {
rows : self.columns,
columns : self.rows,
data : vec![],
};
for j in 0..self.columns {
for i in 0..self.rows {
new_mat.data.push(self.get(i, j)); // We iterate ROW MAJOR across this and push it for column major access.
}
}
new_mat
}
fn element_unary_op(&self, f : Box<Fn(f32)->f32>) -> Matrix {
let mut new_mat = Matrix {
rows : self.rows,
columns : self.columns,
data : vec![]
};
for i in 0..self.rows {
for j in 0..self.columns {
new_mat.data.push(f(self.get(i, j)));
}
}
new_mat
}
fn element_unary_op_i(&mut self, f : Box<Fn(f32)->f32>) {
for i in 0..self.rows {
for j in 0..self.columns {
let v = f(self.get(i, j));
self.set(i, j, v);
}
}
}
fn element_binary_op(&self, other : &Matrix, f : Box<Fn(f32, f32)->f32>) -> Matrix {
assert_eq!(self.rows, other.rows);
assert_eq!(self.columns, other.columns);
let mut new_mat = Matrix {
rows : self.rows,
columns : self.columns,
data : vec![]
};
for i in 0..self.rows {
for j in 0..self.columns {
new_mat.data.push(f(self.get(i, j), other.get(i, j)));
}
}
new_mat
}
fn element_binary_op_i(&mut self, other : &Matrix, f : Box<Fn(f32, f32)->f32>) {
assert_eq!(self.rows, other.rows);
assert_eq!(self.columns, other.columns);
for i in 0..self.rows {
for j in 0..self.columns {
let v = f(self.get(i, j), other.get(i, j));
self.set(i, j, v);
}
}
}
fn multiply(&self, other : &Matrix) -> Matrix {
assert_eq!(self.columns, other.rows);
let mut new_mat = Matrix {
rows : self.rows,
columns : other.columns,
data : vec![]
};
for i in 0..self.rows {
for j in 0..other.columns {
let mut accumulator = 0.0;
for k in 0..self.columns {
accumulator += self.get(i, k)*other.get(k, j);
}
new_mat.data.push(accumulator);
}
}
new_mat
}
}
/*
impl fmt::Display for Matrix {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {} ", self.rows, self.columns);
for i in 0..self.data.len() {
write!(f, "{} ", self.data[i]);
}
write!(f, "\n")
}
}
*/
impl FromStr for Matrix { // Given a matrix in the above format.
type Err = ();
fn from_str(s : &str) -> Result<Matrix, Self::Err> {
let mut s_iter = s.split(" ");
let rows = usize::from_str(s_iter.next().unwrap()).unwrap();
let columns = usize::from_str(s_iter.next().unwrap()).unwrap();
let mut data = vec![];
for v in s_iter {
data.push(f32::from_str(v).unwrap());
}
let new_mat = Matrix { rows : rows, columns : columns, data : data };
Ok(new_mat)
}
}
//
// RNN
//
#[derive(Clone, RustcDecodable, RustcEncodable)]
pub struct RNN {
weight_ih : Matrix,
weight_hh : Matrix,
weight_ho : Matrix,
bias_h : Matrix,
bias_o : Matrix,
hidden_state : Matrix,
}
impl RNN {
fn new(input_size : usize, hidden_size : usize) -> RNN {
let scale : f32 = 0.1;
//let random_constructor = Box::new(|i,j| { let mut rng = rand::thread_rng(); rng.gen::<f32>()*0.1 });
RNN {
weight_ih : Matrix::new_random(input_size, hidden_size, scale),
weight_hh : Matrix::new_random(hidden_size, hidden_size, scale),
weight_ho : Matrix::new_random(hidden_size, input_size, scale),
//weight_ho : Matrix { rows : hidden_size, columns : input_size, data : (0..hidden_size*input_size).into_iter().map(|x| { rng.gen::<f32>()*scale }).collect() },
bias_h : Matrix::new_random(1, hidden_size, scale),
bias_o : Matrix::new_random(1, input_size, scale),
hidden_state : Matrix { rows: 1, columns : hidden_size, data : vec![0.0; hidden_size] }
}
}
fn reset_hidden_state(&mut self) {
for i in 0..self.hidden_state.data.len() {
self.hidden_state.data[i] = 0.0;
}
}
fn set_hidden_state(&mut self, state : Vec<f32>) {
self.hidden_state.data.copy_from_slice(&state)
}
fn get_hidden_state(&self) -> Vec<f32> {
self.hidden_state.data.clone()
}
fn step(&mut self, input_example : &Vec<f32>) -> Vec<f32> {
let input_mat = Matrix::new_from_row(input_example);
// Multiply hidden activity through the system.
let mut new_hidden_accumulator = input_mat.multiply(&self.weight_ih); // x * Wih
new_hidden_accumulator.element_binary_op_i(&self.hidden_state.multiply(&self.weight_hh), Box::new(|a, b|{a+b})); // + h * Whh
new_hidden_accumulator.element_binary_op_i(&self.bias_h, Box::new(|a, b|{a+b})); // + hb
new_hidden_accumulator.element_unary_op_i(Box::new(|a|{ a.tanh() })); // tanh(x*Wih + h*Whh + hb)
// Copy hidden data back into the hidden state.
// self.hidden_state.data = new_hidden_accumulator.data, maybe?
self.hidden_state.data.copy_from_slice(&new_hidden_accumulator.data);
// Multiply for new output.
let mut result = self.hidden_state.multiply(&self.weight_ho);
result.element_binary_op_i(&self.bias_o, Box::new(|a, b|{a+b}));
result.data
}
fn get_last_output(&self) -> Vec<f32> {
let mut result = self.hidden_state.multiply(&self.weight_ho);
result.element_binary_op_i(&self.bias_o, Box::new(|a, b|{a+b}));
result.data
}
}
/*
impl fmt::Display for RNN {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
"{}\n{}\n{}\n{}\n{}",
self.weight_ih,
self.weight_hh,
self.weight_ho,
self.bias_h,
self.bias_o
)
}
}
*/
/*
impl Iterator for RNN {
type Item = Vec<f32>;
fn next(&mut self) -> Option<Vec<f32>> {
}
}
*/
fn loss_function(rnn : &mut RNN, example : &Vec<f32>, target : &Vec<f32>) -> (f32, Matrix, Matrix, Matrix, Matrix, Matrix) {
// NOTE: No reset here.
// Forward pass.
/*
xs[t] = np.zeros((vocab_size,1)) # encode in 1-of-k representation
xs[t][inputs[t]] = 1
hs[t] = np.tanh(np.dot(Wxh, xs[t]) + np.dot(Whh, hs[t-1]) + bh) # hidden state
ys[t] = np.dot(Why, hs[t]) + by # unnormalized log probabilities for next chars
ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) # probabilities for next chars
loss += -np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss)
*/
let mut output = rnn.step(&example); // Gives us ys.
let error : Vec<f32> = target.into_iter().zip(output.into_iter()).map(|d| { d.1 - d.0 }).collect(); // Want this to be how far from the truth we are. If out was [0.1, 0.9] and truth was [0.0, 1.0], this would be [0.1, -0.1]
let loss : f32 = error.clone().into_iter().fold(0.0, |sum, difference| { sum + difference.powi(2) }); // Fold squared error together.
// Backwards pass.
/*
# backward pass: compute gradients going backwards
dWxh, dWhh, dWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why)
dbh, dby = np.zeros_like(bh), np.zeros_like(by)
dhnext = np.zeros_like(hs[0])
for t in reversed(xrange(len(inputs))):
dy = np.copy(ps[t])
dy[targets[t]] -= 1 # backprop into y. see http://cs231n.github.io/neural-networks-case-study/#grad if confused here
dWhy += np.dot(dy, hs[t].T)
dby += dy
dh = np.dot(Why.T, dy) + dhnext # backprop into h
dhraw = (1 - hs[t] * hs[t]) * dh # backprop through tanh nonlinearity
dbh += dhraw
dWxh += np.dot(dhraw, xs[t].T)
dWhh += np.dot(dhraw, hs[t-1].T)
dhnext = np.dot(Whh.T, dhraw)
for dparam in [dWxh, dWhh, dWhy, dbh, dby]:
np.clip(dparam, -5, 5, out=dparam) # clip to mitigate exploding gradients
return loss, dWxh, dWhh, dWhy, dbh, dby, hs[len(inputs)-1]
*/
//println!("RNN State shapes: Wih: {} {}", rnn.weight_ih.rows, rnn.weight_ih.columns);
//println!("RNN State shapes: Whh: {} {}", rnn.weight_hh.rows, rnn.weight_hh.columns);
//println!("RNN State shapes: Who: {} {}", rnn.weight_ho.rows, rnn.weight_ho.columns);
let delta_y = Matrix::new_from_row(&error);
let delta_bias_y = Matrix::new_from_row(&error); // Also delta y.
//println!("Delta y shape: {} {}", delta_y.rows, delta_y.columns);
let delta_weight_hy = rnn.hidden_state.transpose().multiply(&delta_y);
//println!("Delta weight hy: {} {}", delta_weight_hy.rows, delta_weight_hy.columns);
let delta_h = delta_y.multiply(&rnn.weight_ho.transpose());
//println!("Delta hidden: {} {}", delta_h.rows, delta_h.columns);
let delta_h_derivative = rnn.hidden_state.element_unary_op(Box::new(|x| { 1.0 - (x*x) })); // Splitting dhraw = (1 - hs[t]*hs[t]) * dh into two lines.
let delta_h_raw = rnn.hidden_state.element_binary_op(&delta_h, Box::new(|a,b| { a*b })); // TODO: op_i?
//println!("Delta hidden raw: {} {}", delta_h_raw.rows, delta_h_raw.columns);
let delta_bias_h = Matrix::new_from_row(&delta_h_raw.data); // Dimensino mismatch?
let x_in = Matrix::new_from_row(&example);
//println!("Dims for multiply: {}x{} and {}x{}", delta_h_raw.rows, delta_h_raw.columns, x_in.rows, x_in.columns);
let delta_weight_xh = x_in.transpose().multiply(&delta_h_raw);
//println!("Delta weight xh: {} {}", delta_weight_xh.rows, delta_weight_xh.columns);
let delta_weight_hh = rnn.hidden_state.transpose().multiply(&delta_h_raw);
// Return final values.
return (loss, delta_weight_xh, delta_weight_hh, delta_weight_hy, delta_bias_h, delta_bias_y);
}
pub fn train_sequence(rnn : &mut RNN, learning_rate : f32, training_data : &[Vec<f32>], label_data : &[Vec<f32>], verbose : bool) {
let lr = learning_rate;
let mut step = 0;
let mut mem_wih = 0.0f32;
let mut mem_whh = 0.0f32;
let mut mem_who = 0.0f32;
let mut mem_bh = 0.0f32;
let mut mem_bo = 0.0f32;
let mut smooth_loss = 0.0f32;
for (ex, target) in training_data.iter().zip(label_data.iter()) {
// Get the loss + errors.
let (loss, mut dwih, mut dwhh, mut dwho, mut dbh, mut dbo) = loss_function(rnn, ex, target);
smooth_loss = 0.99 * smooth_loss + 0.01 * loss;
if verbose {
println!("Step {} - Loss {} - Smooth loss: {}", step, loss, smooth_loss);
}
// Weight clipping to keep from going crazy.
dwih.element_unary_op_i(Box::new(|x| { if x < -5.0f32 { -5.0f32 } else if x > 5.0f32 { 5.0f32 } else { x } } ) );
dwhh.element_unary_op_i(Box::new(|x| { if x < -5.0f32 { -5.0f32 } else if x > 5.0f32 { 5.0f32 } else { x } } ) );
dwho.element_unary_op_i(Box::new(|x| { if x < -5.0f32 { -5.0f32 } else if x > 5.0f32 { 5.0f32 } else { x } } ) );
dbh.element_unary_op_i(Box::new(|x| { if x < -5.0f32 { -5.0f32 } else if x > 5.0f32 { 5.0f32 } else { x } } ) );
dbo.element_unary_op_i(Box::new(|x| { if x < -5.0f32 { -5.0f32 } else if x > 5.0f32 { 5.0f32 } else { x } } ) );
/*
for param, dparam, mem in zip([Wxh, Whh, Why, bh, by], [dWxh, dWhh, dWhy, dbh, dby], [mWxh, mWhh, mWhy, mbh, mby]):
mem += dparam * dparam
param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update
*/
// Calculate the squared magnitude of all the weight update parameters.
for v in &dwih.data { mem_wih += v*v; }
for v in &dwhh.data { mem_whh += v*v; }
for v in &dwho.data { mem_who += v*v; }
for v in &dbh.data { mem_bh += v*v; }
for v in &dbo.data { mem_bo += v*v; }
// Apply gradients.
rnn.weight_ih.element_binary_op_i(&dwih, Box::new(move |a, b|{a - (b*lr/(1.0e-8 + mem_wih.clone().sqrt()))}));
rnn.weight_hh.element_binary_op_i(&dwhh, Box::new(move |a, b|{a - (b*lr/(1.0e-8 + mem_whh.clone().sqrt()))}));
rnn.weight_ho.element_binary_op_i(&dwho, Box::new(move |a, b|{a - (b*lr/(1.0e-8 + mem_who.clone().sqrt()))}));
rnn.bias_h.element_binary_op_i(&dbh, Box::new(move |a, b|{a - (b*lr/(1.0e-8 + mem_bh.clone().sqrt()))}));
rnn.bias_o.element_binary_op_i(&dbo, Box::new(move |a, b|{a - (b*lr/(1.0e-8 + mem_bo.clone().sqrt()))}));
step += 1;
}
//lr *= learning_decay;
}
//
// BEGIN C API
//
const INPUT_SIZE : usize = 28; // 26 Letters, space, EOL.
const SPACE_CHARACTER : usize = 26;
const TERMINAL_CHARACTER : usize = 27;
const ASCII_a : u8 = 97; // Lower-case is 97.
const ASCII_z : u8 = 122;
const ASCII_SPACE : u8 = 32;
// Helpers.
fn string_to_vector(s : &str) -> Vec<Vec<f32>> {
let mut result : Vec<Vec<f32>> = vec![];
for c in s.to_lowercase().as_bytes() {
let mut char_vector = vec![0.0f32; INPUT_SIZE];
if *c >= ASCII_a && *c <= ASCII_z {
char_vector[(c - ASCII_a) as usize] = 1.0;
} else if *c == ASCII_SPACE {
char_vector[SPACE_CHARACTER] = 1.0;
}
result.push(char_vector);
}
// Append the end of line marker.
let mut terminal_vector = vec![0.0f32; INPUT_SIZE];
terminal_vector[TERMINAL_CHARACTER] = 1.0;
result.push(terminal_vector);
result
}
fn vector_to_string(v : Vec<Vec<f32>>) -> String {
const CHARS : [char;28] = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ', '\0'];
let mut res = String::new();
// res.push("asdf")
for character_distribution in v.iter() {
// Randomly select from the distribution, assuming uniform.
let total_energy = character_distribution.iter().fold(0.0f32, |sum, x| { sum + x });
let mut energy = rand::random::<f32>() * total_energy;
// For each of the entries in the distribution...
for (index, candidate) in character_distribution.iter().enumerate() {
// If the candidate energy is greater than this bump, lose that energy and continue.
if energy > *candidate {
energy -= *candidate;
} else {
assert!(index >= 0 && index < CHARS.len());
// We have selected a character.
if index == TERMINAL_CHARACTER {
return res; // Break early.
} else {
//res.push(std::char::from_u32((ASCII_a as usize + index) as u32).unwrap());
res.push(CHARS[index]);
energy = 0.0;
}
break;
}
}
}
res
}
#[no_mangle]
pub extern "C" fn build_rnn(hidden_layer_size : usize) -> *mut RNN {
// Train our RNN.
let mut rnn = RNN::new(INPUT_SIZE, hidden_layer_size);
Box::into_raw(Box::new(rnn))
}
#[no_mangle]
pub extern "C" fn train_rnn_with_corpus(rnn_ptr : *mut RNN, corpus : *const c_char, delimiter : char, iterations : u32, learning_rate : f32, learning_decay : f32, verbose : bool) {
let mut lr = learning_rate;
let mut rnn = unsafe {
assert!(!rnn_ptr.is_null());
&mut *rnn_ptr
};
// Split up our corpus.
let strings : &str = unsafe {
assert!(!corpus.is_null());
CStr::from_ptr(corpus) // use from_raw(corpus) if CString
}.to_str().expect("Got bad value in corpus.");
//"foo\rbar\nbaz\rquux".split('\n').flat_map(|x| x.split('\r')).collect::<Vec<_>>()
for _ in 0..iterations {
for s in strings.split(delimiter) {
if verbose {
println!("Training sample: '{}'", &s);
}
let training_sample = string_to_vector(&s);
// Convert Vec<Vec<f32>> to &[Vec<f32>] for learning..
rnn.reset_hidden_state();
train_sequence(&mut rnn, lr, &training_sample[..], &training_sample[1..], verbose);
}
lr *= learning_decay;
}
}
#[no_mangle]
pub extern "C" fn sample(rnn_ptr : *mut RNN, output_length : usize, result_buffer : *mut c_char) {
let mut rnn = unsafe {
assert!(!rnn_ptr.is_null());
&mut *rnn_ptr
};
// Start with an empty initialization vector and whatever is in RNN.
let initial_vector_size = rnn.weight_ih.rows;
let mut samples = Vec::<Vec<f32>>::new();
samples.push(rnn.get_last_output());
for _ in 0..output_length {
let last_sample = samples.last().unwrap().clone();
samples.push(rnn.step(&last_sample));
}
// Convert our samples to a string.
let s = vector_to_string(samples);
// Copy the string into the target array.
unsafe {
ptr::copy_nonoverlapping(s.as_ptr() as *mut i8, result_buffer, cmp::min(s.len(), output_length)); // as_bytes_with_nul()?
/*
let mut raw_array = slice::from_raw_parts_mut(result_buffer, output_length);
for (i, chr) in s.bytes().enumerate() {
raw_array[i] = chr as i8;
}
mem::forget(raw_array); // To prevent freeing?
*/
}
}
#[no_mangle]
pub extern "C" fn transform_document(rnn_ptr : *mut RNN, document : *const c_char, reset_rnn : bool, target_output : *mut c_float) {
let mut rnn = unsafe {
assert!(!rnn_ptr.is_null());
&mut *rnn_ptr
};
let doc = unsafe {
assert!(!document.is_null());
//CString::from_raw(document) // Or CStr, but we dont' want &str
CStr::from_ptr(document)
}.to_str().unwrap();
// Reset RNN.
if reset_rnn {
rnn.reset_hidden_state();
}
// Process string.
let doc_vector = string_to_vector(&doc);
for v in doc_vector {
rnn.step(&v);
}
// Return hidden state.
unsafe {
let mut raw_array = slice::from_raw_parts_mut(target_output, rnn.hidden_state.data.len());
for i in 0..rnn.hidden_state.data.len() {
raw_array[i] = rnn.hidden_state.data[i];
}
mem::forget(raw_array); // To prevent freeing?
}
}
#[no_mangle]
pub extern "C" fn load_rnn(c_filename : *const c_char) -> *mut RNN {
let filename = unsafe {
CStr::from_ptr(c_filename)
}.to_str().unwrap();
let mut f = File::open(filename).expect("Invalid filename provided to load_rnn.");
let mut rnn_string = String::new();
f.read_to_string(&mut rnn_string).expect("Problem reading from file.");
let new_rnn : RNN = json::decode(&rnn_string).unwrap();
Box::into_raw(Box::new(new_rnn))
}
#[no_mangle]
pub extern "C" fn save_rnn(rnn_ptr : *const RNN, c_filename : *const c_char) {
let rnn : &RNN = unsafe {
assert!(!rnn_ptr.is_null());
& *rnn_ptr
};
let filename = unsafe {
CStr::from_ptr(c_filename)
}.to_str().unwrap();
let mut f = File::create(filename).expect("Error opening file for write in save_rnn.");
let rnn_string = json::encode(&rnn).expect("Critical problem encoding RNN into JSON. Please report this bug.");
f.write_all(&rnn_string.as_bytes()).expect("Problem writing to output file.");
}
#[no_mangle]
pub extern "C" fn free_rnn(rnn_ptr : *mut RNN) {
let rnn = unsafe {
if rnn_ptr.is_null() { return; }
&*rnn_ptr
};
}
//
// TESTS
//
#[cfg(test)]
mod tests {
use super::{Matrix, RNN, train_sequence, vector_to_string, string_to_vector};
use rustc_serialize::json;
//use super::*;
#[test]
fn test_ident() {
//test_method("Foooo!");
// Verify that the ident behaves as we expect.
let ident = Matrix { rows : 3, columns : 3, data : vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] };
let ident_maybe = Matrix::new_from_fn(3, 3, Box::new(|i,j| { if i==j { 1.0 } else { 0.0 }}));
assert!(ident.data == ident_maybe.data);
let step = Matrix { rows : 3, columns : 4, data : (0..12u32).into_iter().map(|x| { x as f32 }).collect() };
let result = ident.multiply(&step);
assert!(result.data == step.data);
}
#[test]
fn test_matmul1() {
let mut a = Matrix::new(3, 4);
let mut b = Matrix::new(4, 5);
a.element_unary_op_i(Box::new(|_| { 1.0f32 })); // set all A to 1.
b.element_unary_op_i(Box::new(|_| { 1.0f32 })); // Set all B to 1.
let c = a.multiply(&b);
assert_eq!(c.rows, 3);
assert_eq!(c.columns, 5);
for i in 0..3*5 {
assert_eq!(c.data[i], 4.0); // ones * ones should all be 4.
}
}
#[test]
#[cfg_attr(not(feature="expensive_tests"), ignore)] // Run with `cargo test --features expensive_tests`
fn test_train_blink_sequence() {
let mut rnn = RNN::new(3, 2);
for _ in 0..10000 {
rnn.reset_hidden_state();
train_sequence(&mut rnn, 0.01, &[vec![1.0, 0.0, 0.0], vec![0.0, 1.0, 0.0], vec![0.0, 0.0, 1.0]], &[vec![0.0, 1.0, 0.0], vec![0.0, 0.0, 1.0], vec![1.0, 0.0, 0.0]], true);
}
//loss_function(&mut rnn, &vec![1.0, 0.0, 0.0], &vec![0.0, 1.0, 0.0]);
rnn.reset_hidden_state();
let next = rnn.step(&vec![1.0, 0.0, 0.0]);
println!("Next: {:?}", next);
assert!(next[0] < 0.1 && next[1] > 0.9 && next[2] < 0.1);
}
#[test]
#[cfg_attr(not(feature="expensive_tests"), ignore)] // Run with `cargo test --features expensive_tests`
fn test_train_test_sequence() {
let mut rnn = RNN::new(28, 10);
let training_vector = string_to_vector("test");
for _ in 0..10000 {
rnn.reset_hidden_state();
train_sequence(&mut rnn, 0.01, &training_vector[..], &training_vector[1..], true);
}
//loss_function(&mut rnn, &vec![1.0, 0.0, 0.0], &vec![0.0, 1.0, 0.0]);
rnn.reset_hidden_state();
let next = rnn.step(&string_to_vector("t")[0]);
let st = vector_to_string(vec![next.clone()]);
println!("Next: {:?} {:}", next, st);
assert_eq!(st, "e");
}
#[test]
fn test_vector_conversion_sanity() {
assert_eq!("foo bar bez bum", vector_to_string(string_to_vector("foo bar bez bum")));
}
#[test]
fn test_json_encode_decode_sanity() {
let rnn = RNN::new(12, 34);
let rnn_str = json::encode(&rnn).unwrap();
let rnn2 : RNN = json::decode(&rnn_str).unwrap();
assert_eq!(rnn.weight_ih.rows, rnn2.weight_ih.rows);
assert_eq!(rnn.weight_ih.columns, rnn2.weight_ih.columns);
assert!(rnn.weight_ih.data == rnn2.weight_ih.data);
assert_eq!(rnn.weight_hh.rows, rnn2.weight_hh.rows);
assert_eq!(rnn.weight_hh.columns, rnn2.weight_hh.columns);
assert!(rnn.weight_hh.data == rnn2.weight_hh.data);
assert_eq!(rnn.weight_ho.rows, rnn2.weight_ho.rows);
assert_eq!(rnn.weight_ho.columns, rnn2.weight_ho.columns);
assert!(rnn.weight_ho.data == rnn2.weight_ho.data);
}
}
|
/// An enum to represent all characters in the EnclosedIdeographicSupplement block.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub enum EnclosedIdeographicSupplement {
/// \u{1f200}: '🈀'
SquareHiraganaHoka,
/// \u{1f201}: '🈁'
SquaredKatakanaKoko,
/// \u{1f202}: '🈂'
SquaredKatakanaSa,
/// \u{1f210}: '🈐'
SquaredCjkUnifiedIdeographDash624b,
/// \u{1f211}: '🈑'
SquaredCjkUnifiedIdeographDash5b57,
/// \u{1f212}: '🈒'
SquaredCjkUnifiedIdeographDash53cc,
/// \u{1f213}: '🈓'
SquaredKatakanaDe,
/// \u{1f214}: '🈔'
SquaredCjkUnifiedIdeographDash4e8c,
/// \u{1f215}: '🈕'
SquaredCjkUnifiedIdeographDash591a,
/// \u{1f216}: '🈖'
SquaredCjkUnifiedIdeographDash89e3,
/// \u{1f217}: '🈗'
SquaredCjkUnifiedIdeographDash5929,
/// \u{1f218}: '🈘'
SquaredCjkUnifiedIdeographDash4ea4,
/// \u{1f219}: '🈙'
SquaredCjkUnifiedIdeographDash6620,
/// \u{1f21a}: '🈚'
SquaredCjkUnifiedIdeographDash7121,
/// \u{1f21b}: '🈛'
SquaredCjkUnifiedIdeographDash6599,
/// \u{1f21c}: '🈜'
SquaredCjkUnifiedIdeographDash524d,
/// \u{1f21d}: '🈝'
SquaredCjkUnifiedIdeographDash5f8c,
/// \u{1f21e}: '🈞'
SquaredCjkUnifiedIdeographDash518d,
/// \u{1f21f}: '🈟'
SquaredCjkUnifiedIdeographDash65b0,
/// \u{1f220}: '🈠'
SquaredCjkUnifiedIdeographDash521d,
/// \u{1f221}: '🈡'
SquaredCjkUnifiedIdeographDash7d42,
/// \u{1f222}: '🈢'
SquaredCjkUnifiedIdeographDash751f,
/// \u{1f223}: '🈣'
SquaredCjkUnifiedIdeographDash8ca9,
/// \u{1f224}: '🈤'
SquaredCjkUnifiedIdeographDash58f0,
/// \u{1f225}: '🈥'
SquaredCjkUnifiedIdeographDash5439,
/// \u{1f226}: '🈦'
SquaredCjkUnifiedIdeographDash6f14,
/// \u{1f227}: '🈧'
SquaredCjkUnifiedIdeographDash6295,
/// \u{1f228}: '🈨'
SquaredCjkUnifiedIdeographDash6355,
/// \u{1f229}: '🈩'
SquaredCjkUnifiedIdeographDash4e00,
/// \u{1f22a}: '🈪'
SquaredCjkUnifiedIdeographDash4e09,
/// \u{1f22b}: '🈫'
SquaredCjkUnifiedIdeographDash904a,
/// \u{1f22c}: '🈬'
SquaredCjkUnifiedIdeographDash5de6,
/// \u{1f22d}: '🈭'
SquaredCjkUnifiedIdeographDash4e2d,
/// \u{1f22e}: '🈮'
SquaredCjkUnifiedIdeographDash53f3,
/// \u{1f22f}: '🈯'
SquaredCjkUnifiedIdeographDash6307,
/// \u{1f230}: '🈰'
SquaredCjkUnifiedIdeographDash8d70,
/// \u{1f231}: '🈱'
SquaredCjkUnifiedIdeographDash6253,
/// \u{1f232}: '🈲'
SquaredCjkUnifiedIdeographDash7981,
/// \u{1f233}: '🈳'
SquaredCjkUnifiedIdeographDash7a7a,
/// \u{1f234}: '🈴'
SquaredCjkUnifiedIdeographDash5408,
/// \u{1f235}: '🈵'
SquaredCjkUnifiedIdeographDash6e80,
/// \u{1f236}: '🈶'
SquaredCjkUnifiedIdeographDash6709,
/// \u{1f237}: '🈷'
SquaredCjkUnifiedIdeographDash6708,
/// \u{1f238}: '🈸'
SquaredCjkUnifiedIdeographDash7533,
/// \u{1f239}: '🈹'
SquaredCjkUnifiedIdeographDash5272,
/// \u{1f23a}: '🈺'
SquaredCjkUnifiedIdeographDash55b6,
/// \u{1f23b}: '🈻'
SquaredCjkUnifiedIdeographDash914d,
/// \u{1f240}: '🉀'
TortoiseShellBracketedCjkUnifiedIdeographDash672c,
/// \u{1f241}: '🉁'
TortoiseShellBracketedCjkUnifiedIdeographDash4e09,
/// \u{1f242}: '🉂'
TortoiseShellBracketedCjkUnifiedIdeographDash4e8c,
/// \u{1f243}: '🉃'
TortoiseShellBracketedCjkUnifiedIdeographDash5b89,
/// \u{1f244}: '🉄'
TortoiseShellBracketedCjkUnifiedIdeographDash70b9,
/// \u{1f245}: '🉅'
TortoiseShellBracketedCjkUnifiedIdeographDash6253,
/// \u{1f246}: '🉆'
TortoiseShellBracketedCjkUnifiedIdeographDash76d7,
/// \u{1f247}: '🉇'
TortoiseShellBracketedCjkUnifiedIdeographDash52dd,
/// \u{1f248}: '🉈'
TortoiseShellBracketedCjkUnifiedIdeographDash6557,
/// \u{1f250}: '🉐'
CircledIdeographAdvantage,
/// \u{1f251}: '🉑'
CircledIdeographAccept,
/// \u{1f260}: '🉠'
RoundedSymbolForFu,
/// \u{1f261}: '🉡'
RoundedSymbolForLu,
/// \u{1f262}: '🉢'
RoundedSymbolForShou,
/// \u{1f263}: '🉣'
RoundedSymbolForXi,
/// \u{1f264}: '🉤'
RoundedSymbolForShuangxi,
/// \u{1f265}: '🉥'
RoundedSymbolForCai,
}
impl Into<char> for EnclosedIdeographicSupplement {
fn into(self) -> char {
match self {
EnclosedIdeographicSupplement::SquareHiraganaHoka => '🈀',
EnclosedIdeographicSupplement::SquaredKatakanaKoko => '🈁',
EnclosedIdeographicSupplement::SquaredKatakanaSa => '🈂',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash624b => '🈐',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash5b57 => '🈑',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash53cc => '🈒',
EnclosedIdeographicSupplement::SquaredKatakanaDe => '🈓',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash4e8c => '🈔',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash591a => '🈕',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash89e3 => '🈖',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash5929 => '🈗',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash4ea4 => '🈘',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6620 => '🈙',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash7121 => '🈚',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6599 => '🈛',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash524d => '🈜',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash5f8c => '🈝',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash518d => '🈞',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash65b0 => '🈟',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash521d => '🈠',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash7d42 => '🈡',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash751f => '🈢',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash8ca9 => '🈣',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash58f0 => '🈤',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash5439 => '🈥',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6f14 => '🈦',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6295 => '🈧',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6355 => '🈨',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash4e00 => '🈩',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash4e09 => '🈪',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash904a => '🈫',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash5de6 => '🈬',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash4e2d => '🈭',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash53f3 => '🈮',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6307 => '🈯',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash8d70 => '🈰',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6253 => '🈱',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash7981 => '🈲',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash7a7a => '🈳',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash5408 => '🈴',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6e80 => '🈵',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6709 => '🈶',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6708 => '🈷',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash7533 => '🈸',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash5272 => '🈹',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash55b6 => '🈺',
EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash914d => '🈻',
EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash672c => '🉀',
EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash4e09 => '🉁',
EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash4e8c => '🉂',
EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash5b89 => '🉃',
EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash70b9 => '🉄',
EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash6253 => '🉅',
EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash76d7 => '🉆',
EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash52dd => '🉇',
EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash6557 => '🉈',
EnclosedIdeographicSupplement::CircledIdeographAdvantage => '🉐',
EnclosedIdeographicSupplement::CircledIdeographAccept => '🉑',
EnclosedIdeographicSupplement::RoundedSymbolForFu => '🉠',
EnclosedIdeographicSupplement::RoundedSymbolForLu => '🉡',
EnclosedIdeographicSupplement::RoundedSymbolForShou => '🉢',
EnclosedIdeographicSupplement::RoundedSymbolForXi => '🉣',
EnclosedIdeographicSupplement::RoundedSymbolForShuangxi => '🉤',
EnclosedIdeographicSupplement::RoundedSymbolForCai => '🉥',
}
}
}
impl std::convert::TryFrom<char> for EnclosedIdeographicSupplement {
type Error = ();
fn try_from(c: char) -> Result<Self, Self::Error> {
match c {
'🈀' => Ok(EnclosedIdeographicSupplement::SquareHiraganaHoka),
'🈁' => Ok(EnclosedIdeographicSupplement::SquaredKatakanaKoko),
'🈂' => Ok(EnclosedIdeographicSupplement::SquaredKatakanaSa),
'🈐' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash624b),
'🈑' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash5b57),
'🈒' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash53cc),
'🈓' => Ok(EnclosedIdeographicSupplement::SquaredKatakanaDe),
'🈔' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash4e8c),
'🈕' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash591a),
'🈖' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash89e3),
'🈗' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash5929),
'🈘' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash4ea4),
'🈙' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6620),
'🈚' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash7121),
'🈛' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6599),
'🈜' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash524d),
'🈝' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash5f8c),
'🈞' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash518d),
'🈟' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash65b0),
'🈠' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash521d),
'🈡' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash7d42),
'🈢' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash751f),
'🈣' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash8ca9),
'🈤' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash58f0),
'🈥' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash5439),
'🈦' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6f14),
'🈧' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6295),
'🈨' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6355),
'🈩' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash4e00),
'🈪' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash4e09),
'🈫' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash904a),
'🈬' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash5de6),
'🈭' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash4e2d),
'🈮' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash53f3),
'🈯' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6307),
'🈰' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash8d70),
'🈱' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6253),
'🈲' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash7981),
'🈳' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash7a7a),
'🈴' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash5408),
'🈵' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6e80),
'🈶' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6709),
'🈷' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash6708),
'🈸' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash7533),
'🈹' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash5272),
'🈺' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash55b6),
'🈻' => Ok(EnclosedIdeographicSupplement::SquaredCjkUnifiedIdeographDash914d),
'🉀' => Ok(EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash672c),
'🉁' => Ok(EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash4e09),
'🉂' => Ok(EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash4e8c),
'🉃' => Ok(EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash5b89),
'🉄' => Ok(EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash70b9),
'🉅' => Ok(EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash6253),
'🉆' => Ok(EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash76d7),
'🉇' => Ok(EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash52dd),
'🉈' => Ok(EnclosedIdeographicSupplement::TortoiseShellBracketedCjkUnifiedIdeographDash6557),
'🉐' => Ok(EnclosedIdeographicSupplement::CircledIdeographAdvantage),
'🉑' => Ok(EnclosedIdeographicSupplement::CircledIdeographAccept),
'🉠' => Ok(EnclosedIdeographicSupplement::RoundedSymbolForFu),
'🉡' => Ok(EnclosedIdeographicSupplement::RoundedSymbolForLu),
'🉢' => Ok(EnclosedIdeographicSupplement::RoundedSymbolForShou),
'🉣' => Ok(EnclosedIdeographicSupplement::RoundedSymbolForXi),
'🉤' => Ok(EnclosedIdeographicSupplement::RoundedSymbolForShuangxi),
'🉥' => Ok(EnclosedIdeographicSupplement::RoundedSymbolForCai),
_ => Err(()),
}
}
}
impl Into<u32> for EnclosedIdeographicSupplement {
fn into(self) -> u32 {
let c: char = self.into();
let hex = c
.escape_unicode()
.to_string()
.replace("\\u{", "")
.replace("}", "");
u32::from_str_radix(&hex, 16).unwrap()
}
}
impl std::convert::TryFrom<u32> for EnclosedIdeographicSupplement {
type Error = ();
fn try_from(u: u32) -> Result<Self, Self::Error> {
if let Ok(c) = char::try_from(u) {
Self::try_from(c)
} else {
Err(())
}
}
}
impl Iterator for EnclosedIdeographicSupplement {
type Item = Self;
fn next(&mut self) -> Option<Self> {
let index: u32 = (*self).into();
use std::convert::TryFrom;
Self::try_from(index + 1).ok()
}
}
impl EnclosedIdeographicSupplement {
/// The character with the lowest index in this unicode block
pub fn new() -> Self {
EnclosedIdeographicSupplement::SquareHiraganaHoka
}
/// The character's name, in sentence case
pub fn name(&self) -> String {
let s = std::format!("EnclosedIdeographicSupplement{:#?}", self);
string_morph::to_sentence_case(&s)
}
}
|
// Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
use super::CONSENSUS_MINER_MIN_POWER;
use crate::{BalanceTable, BytesKey, Multimap, Set, StoragePower, HAMT_BIT_WIDTH};
use address::Address;
use cid::Cid;
use clock::ChainEpoch;
use encoding::Cbor;
use ipld_blockstore::BlockStore;
use ipld_hamt::Hamt;
use num_bigint::biguint_ser::{BigUintDe, BigUintSer};
use num_traits::{CheckedSub, Zero};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use vm::{Serialized, TokenAmount};
/// Storage power actor state
#[derive(Default)]
pub struct State {
pub total_network_power: StoragePower,
pub miner_count: i64,
/// The balances of pledge collateral for each miner actually held by this actor.
/// The sum of the values here should always equal the actor's balance.
/// See Claim for the pledge *requirements* for each actor.
pub escrow_table: Cid, // BalanceTable (HAMT[address]TokenAmount)
/// A queue of events to be triggered by cron, indexed by epoch.
pub cron_event_queue: Cid, // Multimap, (HAMT[ChainEpoch]AMT[CronEvent]
/// Last chain epoch OnEpochTickEnd was called on
pub last_epoch_tick: ChainEpoch,
/// Miners having failed to prove storage.
pub post_detected_fault_miners: Cid, // Set, HAMT[addr.Address]struct{}
/// Claimed power and associated pledge requirements for each miner.
pub claims: Cid, // Map, HAMT[address]Claim
/// Number of miners having proven the minimum consensus power.
// TODO: revisit todo in specs-actors
pub num_miners_meeting_min_power: i64,
}
impl State {
pub fn new(empty_map_cid: Cid) -> State {
State {
escrow_table: empty_map_cid.clone(),
cron_event_queue: empty_map_cid.clone(),
post_detected_fault_miners: empty_map_cid.clone(),
claims: empty_map_cid,
..Default::default()
}
}
/// Get miner balance from address using escrow table
#[allow(dead_code)]
pub(super) fn get_miner_balance<BS: BlockStore>(
&self,
store: &BS,
miner: &Address,
) -> Result<TokenAmount, String> {
let bt = BalanceTable::from_root(store, &self.escrow_table)?;
bt.get(miner)
}
/// Sets miner balance at address using escrow table
#[allow(dead_code)]
pub(super) fn set_miner_balance<BS: BlockStore>(
&mut self,
store: &BS,
miner: &Address,
amount: TokenAmount,
) -> Result<(), String> {
let mut bt = BalanceTable::from_root(store, &self.escrow_table)?;
bt.set(miner, amount)?;
self.escrow_table = bt.root()?;
Ok(())
}
/// Adds amount to miner balance at address using escrow table
pub(super) fn add_miner_balance<BS: BlockStore>(
&mut self,
store: &BS,
miner: &Address,
amount: &TokenAmount,
) -> Result<(), String> {
let mut bt = BalanceTable::from_root(store, &self.escrow_table)?;
bt.add(miner, amount)?;
self.escrow_table = bt.root()?;
Ok(())
}
/// Subtracts amount to miner balance at address using escrow table
#[allow(dead_code)]
pub(super) fn subtract_miner_balance<BS: BlockStore>(
&mut self,
store: &BS,
miner: &Address,
amount: &TokenAmount,
balance_floor: &TokenAmount,
) -> Result<TokenAmount, String> {
let mut bt = BalanceTable::from_root(store, &self.escrow_table)?;
let amount = bt.subtract_with_minimum(miner, amount, balance_floor)?;
self.escrow_table = bt.root()?;
Ok(amount)
}
pub fn subtract_from_claim<BS: BlockStore>(
&mut self,
store: &BS,
miner: &Address,
power: &StoragePower,
pledge: &TokenAmount,
) -> Result<(), String> {
let mut claim = self
.get_claim(store, miner)?
.ok_or(format!("no claim for actor {}", miner))?;
let old_nominal_power = self.compute_nominal_power(store, miner, &claim.power)?;
claim.power -= power;
claim.pledge = claim
.pledge
.checked_sub(pledge)
.ok_or("negative claimed pledge")?;
self.update_claim(store, miner, power, claim, old_nominal_power)
}
pub fn add_to_claim<BS: BlockStore>(
&mut self,
store: &BS,
miner: &Address,
power: &StoragePower,
pledge: &TokenAmount,
) -> Result<(), String> {
let mut claim = self
.get_claim(store, miner)?
.ok_or(format!("no claim for actor {}", miner))?;
let old_nominal_power = self.compute_nominal_power(store, miner, &claim.power)?;
claim.power += power;
claim.pledge += pledge;
self.update_claim(store, miner, power, claim, old_nominal_power)
}
/// Function will update the claim after `add_to_claim` or `subtract_from_claim` are called
/// * Logic is modified from spec to not use negative values
/// TODO revisit: logic for parts of this function seem wrong/ unnecessary
fn update_claim<BS: BlockStore>(
&mut self,
store: &BS,
miner: &Address,
power: &StoragePower,
claim: Claim,
old_nominal_power: StoragePower,
) -> Result<(), String> {
let new_nominal_power = self.compute_nominal_power(store, miner, &claim.power)?;
let min_power_ref: &StoragePower = &CONSENSUS_MINER_MIN_POWER;
let prev_below: bool = &old_nominal_power < min_power_ref;
let still_below: bool = &new_nominal_power < min_power_ref;
let faulty = self.has_detected_fault(store, miner)?;
if !faulty {
if prev_below && !still_below {
// Just passed min miner size
self.num_miners_meeting_min_power += 1;
self.total_network_power += new_nominal_power;
} else if !prev_below && still_below {
// just went below min miner size
self.num_miners_meeting_min_power -= 1;
self.total_network_power = self
.total_network_power
.checked_sub(&old_nominal_power)
.ok_or("Negative nominal power")?;
} else if !prev_below && !still_below {
// Was above the threshold, still above
self.total_network_power += power;
}
}
if self.num_miners_meeting_min_power < 0 {
return Err(format!(
"negative number of miners: {}",
self.num_miners_meeting_min_power
));
}
self.set_claim(store, miner, claim)
}
/// Gets claim from claims map by address
pub fn get_claim<BS: BlockStore>(
&self,
store: &BS,
a: &Address,
) -> Result<Option<Claim>, String> {
let map: Hamt<BytesKey, _> =
Hamt::load_with_bit_width(&self.claims, store, HAMT_BIT_WIDTH)?;
Ok(map.get(&a.to_bytes())?)
}
pub(super) fn set_claim<BS: BlockStore>(
&mut self,
store: &BS,
addr: &Address,
claim: Claim,
) -> Result<(), String> {
let mut map: Hamt<BytesKey, _> =
Hamt::load_with_bit_width(&self.claims, store, HAMT_BIT_WIDTH)?;
map.set(addr.to_bytes().into(), claim)?;
self.claims = map.flush()?;
Ok(())
}
pub(super) fn delete_claim<BS: BlockStore>(
&mut self,
store: &BS,
addr: &Address,
) -> Result<(), String> {
let mut map: Hamt<BytesKey, _> =
Hamt::load_with_bit_width(&self.claims, store, HAMT_BIT_WIDTH)?;
map.delete(&addr.to_bytes())?;
self.claims = map.flush()?;
Ok(())
}
fn compute_nominal_power<BS: BlockStore>(
&self,
store: &BS,
miner: &Address,
claimed_power: &StoragePower,
) -> Result<StoragePower, String> {
// Compute nominal power: i.e., the power we infer the miner to have (based on the network's
// PoSt queries), which may not be the same as the claimed power.
// Currently, the nominal power may differ from claimed power because of
// detected faults.
let found = self.has_detected_fault(store, miner)?;
if found {
Ok(StoragePower::zero())
} else {
Ok(claimed_power.clone())
}
}
pub(super) fn has_detected_fault<BS: BlockStore>(
&self,
store: &BS,
a: &Address,
) -> Result<bool, String> {
let faulty = Set::from_root(store, &self.post_detected_fault_miners)?;
Ok(faulty.has(&a.to_bytes())?)
}
pub(super) fn put_detected_fault<BS: BlockStore>(
&mut self,
s: &BS,
a: &Address,
) -> Result<(), String> {
let claim = self
.get_claim(s, a)?
.ok_or(format!("no claim for actor: {}", a))?;
let nominal_power = self.compute_nominal_power(s, a, &claim.power)?;
if nominal_power >= *CONSENSUS_MINER_MIN_POWER {
self.num_miners_meeting_min_power -= 1;
}
let mut faulty_miners = Set::from_root(s, &self.post_detected_fault_miners)?;
faulty_miners.put(a.to_bytes().into())?;
self.post_detected_fault_miners = faulty_miners.root()?;
Ok(())
}
pub(super) fn delete_detected_fault<BS: BlockStore>(
&mut self,
s: &BS,
a: &Address,
) -> Result<(), String> {
let mut faulty_miners = Set::from_root(s, &self.post_detected_fault_miners)?;
faulty_miners.delete(&a.to_bytes())?;
self.post_detected_fault_miners = faulty_miners.root()?;
let claim = self
.get_claim(s, a)?
.ok_or(format!("no claim for actor: {}", a))?;
let nominal_power = self.compute_nominal_power(s, a, &claim.power)?;
if nominal_power >= *CONSENSUS_MINER_MIN_POWER {
self.num_miners_meeting_min_power += 1;
self.total_network_power += claim.power;
}
Ok(())
}
pub(super) fn append_cron_event<BS: BlockStore>(
&mut self,
s: &BS,
epoch: ChainEpoch,
event: CronEvent,
) -> Result<(), String> {
let mut mmap = Multimap::from_root(s, &self.cron_event_queue)?;
mmap.add(epoch_key(epoch), event)?;
self.cron_event_queue = mmap.root()?;
Ok(())
}
pub(super) fn load_cron_events<BS: BlockStore>(
&mut self,
s: &BS,
epoch: ChainEpoch,
) -> Result<Vec<CronEvent>, String> {
let mut events = Vec::new();
let mmap = Multimap::from_root(s, &self.cron_event_queue)?;
mmap.for_each(&epoch_key(epoch), |_, v: &CronEvent| {
match self.get_claim(s, &v.miner_addr) {
Ok(Some(_)) => events.push(v.clone()),
Err(e) => {
return Err(format!(
"failed to find claimed power for {} for cron event: {}",
v.miner_addr, e
))
}
_ => (), // ignore events for defunct miners.
}
Ok(())
})?;
Ok(events)
}
pub(super) fn clear_cron_events<BS: BlockStore>(
&mut self,
s: &BS,
epoch: ChainEpoch,
) -> Result<(), String> {
let mut mmap = Multimap::from_root(s, &self.cron_event_queue)?;
mmap.remove_all(&epoch_key(epoch))?;
self.cron_event_queue = mmap.root()?;
Ok(())
}
}
fn epoch_key(e: ChainEpoch) -> BytesKey {
// TODO switch logic to flip bits on negative value before encoding if ChainEpoch changed to i64
// and add tests for edge cases once decided
let ux = e << 1;
let mut bz = unsigned_varint::encode::u64_buffer();
unsigned_varint::encode::u64(ux, &mut bz);
bz.to_vec().into()
}
impl Cbor for State {}
impl Serialize for State {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(
BigUintDe(self.total_network_power.clone()),
&self.miner_count,
&self.escrow_table,
&self.cron_event_queue,
&self.last_epoch_tick,
&self.post_detected_fault_miners,
&self.claims,
&self.num_miners_meeting_min_power,
)
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for State {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (
BigUintDe(total_network_power),
miner_count,
escrow_table,
cron_event_queue,
last_epoch_tick,
post_detected_fault_miners,
claims,
num_miners_meeting_min_power,
) = Deserialize::deserialize(deserializer)?;
Ok(Self {
total_network_power,
miner_count,
escrow_table,
cron_event_queue,
last_epoch_tick,
post_detected_fault_miners,
claims,
num_miners_meeting_min_power,
})
}
}
#[derive(Default, Debug)]
pub struct Claim {
pub power: StoragePower,
pub pledge: TokenAmount,
}
impl Serialize for Claim {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(BigUintSer(&self.power), BigUintSer(&self.pledge)).serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Claim {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (BigUintDe(power), BigUintDe(pledge)) = Deserialize::deserialize(deserializer)?;
Ok(Self { power, pledge })
}
}
#[derive(Clone, Debug)]
pub struct CronEvent {
pub miner_addr: Address,
pub callback_payload: Serialized,
}
impl Cbor for CronEvent {}
impl Serialize for CronEvent {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
(&self.miner_addr, &self.callback_payload).serialize(serializer)
}
}
impl<'de> Deserialize<'de> for CronEvent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let (miner_addr, callback_payload) = Deserialize::deserialize(deserializer)?;
Ok(Self {
miner_addr,
callback_payload,
})
}
}
|
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::pin::Pin;
use std::task::{Context, Poll};
use futures::{FutureExt, Stream};
use pin_project_lite::pin_project;
use tokio_stream::{self as stream, StreamExt};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_util::codec::{Decoder, Framed};
mod frame;
type BoxError = Box<dyn std::error::Error + Send + Sync>;
/// https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=aca313baa32468cf28af564883941b83
#[tokio::main]
async fn main() {
let mut stream = stream::iter(vec![0, 1, 2]);
while let Some(value) = stream.map(|x| x * 2).next().await {
println!("Got {}", value);
}
}
fn process(message: Message) -> Reslut<Message, BoxError> {
Result::Ok(())
}
pub struct Server<I, S, P> {
channels: Vec<Channel<I, S, P>>
}
pub struct Channel<I, S, P> {
conn: I,
proto: P,
// 持有的用户最终handler,async_fn_handler()
inner: S,
}
#[derive(Debug)]
pub struct Message {}
impl Display for Message {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
todo!()
}
}
impl <I, S, P> Channel<I, S, P>
where
S: Handle<S>
{
// 改造为builder模式
fn handle(conn:I, proto: P, handle : S) -> Channel<I, S, P> {
Channel {
conn,
proto,
inner: handle,
}
}
}
// 根据proto和transport 包装桥接framed
// framed -> framed_inbound_handler -> other_inbound_handler ->
// incoming <=> channel <=> | error | fn_handler(A)-> Option<B> -> Option<None>如何处理
// framed <- framed_outbound_handler <- other_outbound_handler <-
pub trait Handle<Message> {
type Item;
type Error;
type Stream : Stream<Item = Option<Result<Self::Item, Self::Error>>>;
type F: FnMut(Message) -> Self::Item;
// 控制处理的速度,是否需要?
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>>;
// 调用上一个stream,用来创建下一个stream
// 每次连接创建一个channel,每个channel调用一次handle链来创建stream
fn process(&mut self, f: Self::F) -> Self::Stream;
}
#[derive(Debug, Clone)]
pub struct FramedHandler<S> {
inner: S,
}
pub fn make_handler<T, U, S>(inner: T, codec: U) -> FramedHandler<S>
where
T: AsyncRead + AsyncWrite,
U: Decoder,
{
FramedHandler {
inner: Framed::new(inner, codec),
}
}
// call的是request,handler的是什么, Message还是Channel
impl<S, U, E> Handle<Message> for FramedHandler<S>
where
U: Decoder,
E: Into<BoxError>,
S: Stream<Item = Result<U::Item, E>>,
{
type Item = U::Item;
type Error = E;
type Stream = S;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn process(&self, message: Message) -> Self::Stream {
println!("message: {}", message);
// 包装handler无法访问process,获取framed
FramedStream {
inner : self.inner
}
}
}
pin_project! {
pub struct FramedStream<S, F> {
#[pin]
inner: S,
#[pin]
f: F
}
}
impl<S, U, E> Stream for FramedStream<S>
where
U: Decoder,
E: Into<BoxError>,
S: Stream<Item = Result<U::Item, E>>,
{
type Item = Result<U::Item, E>;
fn poll_next(self: &mut Self, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
// 包装stream默认同被包装状态相同
match self.project().inner.poll_next(cx) {
Poll::Ready(t) => Poll::Ready(t),
Poll::Pending => Poll::Pending,
}
// timeout是在pending时计时
}
}
|
use pest::Parser;
use super::*;
#[derive(Parser)]
#[grammar = "conventional_commit.pest"]
struct ConventionalCommitParser;
pub(crate) fn parse(commit_msg: &str) -> Option<Change> {
let commit = ConventionalCommitParser::parse(Rule::conventional_commit, commit_msg)
.ok()?
.next()?;
let mut result = Change::new(ChangeType::Fix, "");
for commit_part in commit.into_inner() {
match commit_part.as_rule() {
Rule::feat => result.type_ = ChangeType::Feature,
Rule::fix => result.type_ = ChangeType::Fix,
Rule::custom_type => result.type_ = ChangeType::Custom(commit_part.as_str()),
Rule::breaking_flag => result.breaking = BreakingInfo::Breaking,
Rule::scope => result.scope = Some(commit_part.as_str()),
Rule::description => result.description = commit_part.as_str(),
Rule::body => result.body = Some(commit_part.as_str()),
Rule::footer => {
let mut is_breaking = false;
let mut footer_content: &str = "";
for footer_part in commit_part.into_inner() {
match footer_part.as_rule() {
Rule::breaking_change_token => is_breaking = true,
Rule::footer_value => footer_content = footer_part.as_str(),
_ => (),
}
}
if is_breaking {
match &mut result.breaking {
BreakingInfo::NotBreaking | BreakingInfo::Breaking => {
result.breaking =
BreakingInfo::BreakingWithDescriptions(vec![footer_content]);
}
BreakingInfo::BreakingWithDescriptions(infos) => {
infos.push(footer_content);
}
}
}
}
_ => (),
}
}
Some(result)
}
|
use super::{
CInputKind, COutputKind, CompilerKind, DCompilerKind, DepKind, DetectOpts, FileKind,
FormatArgs, LdScript, PlatformKind, SizeInfo, ToolchainOpts,
};
use crate::{
qjs,
system::{check_access, exec_out, which_any, write_file, AccessMode, Path, PathBuf},
Actual, Artifact, ArtifactStore, BoxedFuture, DataHasher, Diagnostics, Directory, Input, Mut,
Output, Ref, Result, Rule, RuleApi, Set, WeakArtifact,
};
use futures::future::{join_all, FutureExt};
use std::iter::once;
macro_rules! log_out {
($res:ident) => {
log_out!(@out $res);
log_out!(@err $res);
};
(@out $res:ident) => {
if !$res.out.is_empty() {
for line in $res.out.split('\n') {
log::warn!("{}", line);
}
}
};
(@err $res:ident) => {
if !$res.err.is_empty() {
for line in $res.err.split('\n') {
log::error!("{}", line);
}
}
};
}
#[derive(Hash)]
struct PropsInternal {
/// C compiler path
cc: String,
/// D compiler path
dc: Option<String>,
/// Archiver path
ar: String,
/// Binutil nm path
nm: String,
/// Binutil size path
size: String,
/// Binutil strip path
strip: String,
objcopy: String,
objdump: String,
readelf: String,
kind: CompilerKind,
version: String,
target: String,
platform: PlatformKind,
}
impl PropsInternal {
async fn new(opts: DetectOpts) -> Result<Self> {
let path = &opts.compiler;
let kind: CompilerKind = path.parse()?;
let (version, target, tools, dc) = match kind {
CompilerKind::Gcc => {
let mut version = exec_out(path, &["-dumpversion"]).await?.success()?.out;
version.retain(|c| c != '\n');
log::debug!("gcc version: {}", version);
let mut target = exec_out(path, &["-dumpmachine"]).await?.success()?.out;
target.retain(|c| c != '\n');
log::debug!("gcc target: {}", target);
async fn find_tool(path: &str, target: &str, name: &str) -> Result<String> {
let pre_path = &path[..path.len() - 3];
let path0 = format!("{}{}", pre_path, name);
let path1 = format!("{}-{}", target, name);
let paths = [path0.as_str(), path1.as_str(), name];
let path = which_any(if pre_path.ends_with("-") {
&paths[..2]
} else {
&paths[..]
})
.await
.ok_or_else(|| format!("Unable to find `{}`", name))?;
check_access(&path, AccessMode::EXECUTE).await?;
Ok(path.display().to_string())
}
let tools = join_all(
[
"gcc-ar", "gcc-nm", "size", "strip", "objcopy", "objdump", "readelf",
]
.iter()
.map(|name| find_tool(&path, &target, name)),
)
.await;
let gdc = find_tool(&path, &target, "gdc")
.await
.map_err(|error| {
log::warn!("{}", error);
})
.ok();
(version, target, tools, gdc)
}
CompilerKind::Llvm => {
let target = if opts.target.is_empty() {
env!("BUILD_TARGET")
} else {
&opts.target
};
let data = exec_out(path, &["-target", target, "--version"])
.await?
.success()?
.out;
let mut lines = data.split('\n');
let version = lines
.next()
.and_then(|line| {
let mut chunks = line.split("clang version ");
chunks
.next()
.and_then(|_| chunks.next())
.and_then(|chunk| chunk.split(' ').next())
})
.ok_or_else(|| format!("Unable to determine clang version"))?
.into();
log::debug!("clang version: {}", version);
let target = lines
.next()
.and_then(|line| {
if line.starts_with("Target:") {
Some(line[7..].trim().into())
} else {
None
}
})
.ok_or_else(|| format!("Unable to determine clang target"))?;
log::debug!("clang target: {}", target);
async fn find_tool(path: &str, name: &str) -> Result<String> {
let mut path = exec_out(path, &["--print-prog-name", name])
.await?
.success()?
.out;
path.retain(|c| c != '\n');
check_access(&path, AccessMode::EXECUTE).await?;
Ok(path)
}
let tools = join_all(
[
"llvm-ar",
"llvm-nm",
"llvm-size",
"llvm-strip",
"llvm-objcopy",
"llvm-objdump",
"llvm-readelf",
]
.iter()
.map(|name| find_tool(path, name)),
)
.await;
let ldc = find_tool(&path, "ldc2")
.await
.map_err(|error| {
log::warn!("{}", error);
})
.ok();
(version, target, tools, ldc)
}
};
let mut paths = tools.into_iter().collect::<Result<Vec<_>>>()?.into_iter();
let ar = paths.next().unwrap();
let nm = paths.next().unwrap();
let size = paths.next().unwrap();
let strip = paths.next().unwrap();
let objcopy = paths.next().unwrap();
let objdump = paths.next().unwrap();
let readelf = paths.next().unwrap();
let platform = PlatformKind::from_target(&target)?;
Ok(Self {
cc: opts.compiler.clone(),
dc,
ar,
nm,
size,
strip,
objcopy,
objdump,
readelf,
kind,
version,
target,
platform,
})
}
}
#[derive(Clone)]
pub struct CompilerConfig(Ref<Internal>);
impl CompilerConfig {
pub fn hash(&self) -> String {
DataHasher::hash_base64_string(&(&self.0.props, &self.0.opts))
}
pub fn base_opts(&self) -> Vec<String> {
let mut out = Vec::default();
self.0.opts.base.fmt_args(&mut out);
out
}
pub fn c_opts(&self) -> Vec<String> {
let mut out = Vec::default();
(&self.0.opts.base, &self.0.opts.cc, &self.0.opts.c).fmt_args(&mut out);
out
}
pub fn cxx_opts(&self) -> Vec<String> {
let mut out = Vec::default();
(&self.0.opts.base, &self.0.opts.cc, &self.0.opts.cxx).fmt_args(&mut out);
out
}
pub fn d_opts(&self) -> Vec<String> {
let mut out = Vec::default();
(self.0.props.kind, &self.0.opts.base, &self.0.opts.d).fmt_args(&mut out);
out
}
pub fn link_opts(&self) -> Vec<String> {
let mut out = Vec::default();
(&self.0.opts.base, &self.0.opts.link).fmt_args(&mut out);
out
}
pub fn dump_opts(&self) -> Vec<String> {
let mut out = Vec::default();
self.0.opts.dump.fmt_args(&mut out);
out
}
pub fn strip_opts(&self) -> Vec<String> {
let mut out = Vec::default();
self.0.opts.strip.fmt_args(&mut out);
out
}
}
#[derive(Clone)]
pub(self) struct Internal {
props: Ref<PropsInternal>,
opts: ToolchainOpts,
}
impl Internal {
pub async fn detect(opts: DetectOpts) -> Result<Self> {
let props = PropsInternal::new(opts).await?;
/*let diag_opts: &[&str] = match props.kind {
CompilerKind::Gcc => &[
//"-fno-diagnostics-show-caret",
//"-fno-diagnostics-color",
//"-fdiagnostics-show-option",
"-fdiagnostics-parseable-fixits",
],
CompilerKind::Llvm => &[
//"-fdiagnostics-format=clang",
//"-fdiagnostics-print-source-range-info",
//"-fno-caret-diagnostics",
//"-fno-color-diagnostics",
//"-fdiagnostics-show-option",
"-fdiagnostics-parseable-fixits",
],
};
for opts in &[&mut compile_opts, &mut link_opts] {
opts.extend(diag_opts);
}*/
Ok(Self {
props: Ref::new(props),
opts: Default::default(),
})
}
pub fn config(&self, new_opts: ToolchainOpts) -> Self {
let mut opts = self.opts.clone();
opts.extend(Some(new_opts));
Self {
props: self.props.clone(),
opts,
}
}
}
#[derive(Debug, Clone, qjs::FromJs, Default)]
pub struct CompileOptions {
pub input: Option<CInputKind>,
pub output: COutputKind,
}
pub(self) struct CompileInternal {
cfg: CompilerConfig,
store: ArtifactStore,
in_kind: CInputKind,
out_kind: COutputKind,
src: Artifact<Input, Actual>,
dep: PathBuf,
incs: Mut<Set<Artifact<Input, Actual>>>,
dst: WeakArtifact<Output, Actual>,
}
impl Drop for CompileInternal {
fn drop(&mut self) {
log::debug!("Compile::drop");
}
}
impl RuleApi for CompileInternal {
fn inputs(&self) -> Vec<Artifact<Input>> {
once(&self.src)
.chain(self.incs.read().iter())
.map(|input| input.clone().into_kind_any())
.collect()
}
fn outputs(&self) -> Vec<Artifact<Output>> {
self.dst
.try_ref()
.map(|input| input.into_kind_any())
.into_iter()
.collect()
}
fn invoke(self: Ref<Self>) -> BoxedFuture<Result<Diagnostics>> {
async move {
log::debug!("Compile::invoke");
Ok(if let Some(dst) = self.dst.try_ref() {
let deps_name = self.dep.display().to_string();
let src = &self.src;
let mut dep_kind = DepKind::default();
let (cmd, args) = if self.in_kind == CInputKind::D {
let mut args = self.cfg.d_opts();
match DCompilerKind::from(self.cfg.0.props.kind) {
DCompilerKind::Gdc => {
args.push(
match self.out_kind {
COutputKind::Asm => "-S",
COutputKind::Obj => "-c",
_ => unreachable!(),
}
.into(),
);
args.push("-MMD".into());
args.push("-MF".into());
args.push(deps_name);
args.push("-o".into());
args.push(dst.name().clone());
args.push(src.name().clone());
}
DCompilerKind::Ldc => {
args.push("--verror-style=gnu".into());
args.push(format!("--mtriple={}", self.cfg.0.props.target));
args.push(format!(
"--output-{}",
match self.out_kind {
COutputKind::Asm => "s",
COutputKind::Obj => "o",
COutputKind::Ir => "ll",
COutputKind::Bc => "bc",
_ => unreachable!(),
}
));
args.push(format!("--deps={}", deps_name));
dep_kind = DepKind::D;
args.push("--op".into());
args.push(format!("--of={}", dst.name()));
args.push(src.name().clone());
}
}
(self.cfg.0.props.dc.as_ref().unwrap(), args)
} else {
fn with_lang(lang: &str, mut args: Vec<String>) -> Vec<String> {
args.push(format!("-x{}", lang));
args
}
let mut args = match self.in_kind {
CInputKind::C => with_lang("c", self.cfg.c_opts()),
CInputKind::Asm => with_lang("assembler-with-cpp", self.cfg.c_opts()),
CInputKind::Cxx => with_lang("c++", self.cfg.cxx_opts()),
_ => unreachable!(),
};
if matches!(self.cfg.0.props.kind, CompilerKind::Llvm) {
args.push(format!("--target={}", self.cfg.0.props.target));
if matches!(self.out_kind, COutputKind::Ir | COutputKind::Bc) {
args.push("--emit-llvm".into());
}
}
args.push(
match self.out_kind {
COutputKind::Cpp => "-E",
COutputKind::Asm | COutputKind::Ir => "-S",
COutputKind::Obj | COutputKind::Bc => "-c",
}
.into(),
);
args.push("-MMD".into());
args.push("-MF".into());
args.push(deps_name);
args.push("-o".into());
args.push(dst.name().clone());
args.push(src.name().clone());
(&self.cfg.0.props.cc, args)
};
let res = exec_out(cmd, &args).await?;
log_out!(res);
let dep_path = &self.dep;
if dep_path.is_file().await {
let src_name = self.src.name();
// reload generated deps
let incs = self
.store
.read_deps(dep_path, dep_kind, |src| src != src_name)
.await?;
*self.incs.write() = incs;
}
res.err.parse()?
} else {
Default::default()
})
}
.boxed_local()
}
}
#[derive(Debug, Clone, qjs::IntoJs)]
pub struct LinkOutput {
pub out: Artifact<Input, Actual>,
pub map: Artifact<Input, Actual>,
}
#[derive(Debug, Clone, Default)]
pub struct LinkOptions {
output: FileKind,
script: Option<Artifact<Input, Actual>>,
}
impl<'js> qjs::FromJs<'js> for LinkOptions {
fn from_js(_ctx: qjs::Ctx<'js>, val: qjs::Value<'js>) -> qjs::Result<Self> {
let obj: qjs::Object = val.get()?;
let output = if obj.contains_key("type")? {
val.get()?
} else {
Default::default()
};
let script = obj.get("script")?;
Ok(Self { output, script })
}
}
pub(self) struct LinkInternal {
cfg: CompilerConfig,
out_kind: FileKind,
objs: Set<Artifact<Input, Actual>>,
script: Option<Artifact<Input, Actual>>,
out: WeakArtifact<Output, Actual>,
map: WeakArtifact<Output, Actual>,
}
impl Drop for LinkInternal {
fn drop(&mut self) {
log::debug!("Link::drop");
}
}
impl RuleApi for LinkInternal {
fn inputs(&self) -> Vec<Artifact<Input>> {
self.script
.iter()
.chain(self.objs.iter())
.map(|input| input.clone().into_kind_any())
.collect()
}
fn outputs(&self) -> Vec<Artifact<Output>> {
self.out
.try_ref()
.map(|input| input.into_kind_any())
.into_iter()
.collect()
}
fn invoke(self: Ref<Self>) -> BoxedFuture<Result<Diagnostics>> {
async move {
log::debug!("Link::invoke");
Ok(if let Some(out) = self.out.try_ref() {
let (cmd, mut args) = if matches!(self.out_kind, FileKind::Static { .. }) {
(&self.cfg.0.props.ar, vec!["cr".into(), out.name().clone()])
} else {
let mut args = self.cfg.link_opts();
args.push("-o".into());
args.push(out.name().clone());
if matches!(self.out_kind, FileKind::Dynamic { .. }) {
args.push("-shared".into());
}
if let Some(script) = &self.script {
args.push("-T".into());
args.push(script.name().clone());
}
if let Some(map) = self.map.try_ref() {
args.push(format!("-Wl,-Map,{}", map.name()));
}
(&self.cfg.0.props.cc, args)
};
args.extend(self.objs.iter().map(|obj| obj.name().clone()));
let res = exec_out(cmd, &args).await?;
log_out!(res);
res.err.parse()?
} else {
Default::default()
})
}
.boxed_local()
}
}
#[derive(Debug, Clone, qjs::IntoJs)]
pub struct StripOutput {
pub out: Artifact<Input, Actual>,
pub strip: Option<Artifact<Input, Actual>>,
}
pub(self) struct StripInternal {
cfg: CompilerConfig,
obj: Artifact<Input, Actual>,
out: WeakArtifact<Output, Actual>,
strip_out: Option<WeakArtifact<Output, Actual>>,
}
impl Drop for StripInternal {
fn drop(&mut self) {
log::debug!("Strip::drop");
}
}
impl RuleApi for StripInternal {
fn inputs(&self) -> Vec<Artifact<Input>> {
vec![self.obj.clone().into_kind_any()]
}
fn outputs(&self) -> Vec<Artifact<Output>> {
self.out
.try_ref()
.map(|input| input.into_kind_any())
.into_iter()
.chain(
self.strip_out
.as_ref()
.and_then(|out| out.try_ref().map(|input| input.into_kind_any())),
)
.collect()
}
fn invoke(self: Ref<Self>) -> BoxedFuture<Result<Diagnostics>> {
async move {
log::debug!("Strip::invoke");
if let Some(out) = self.out.try_ref() {
let mut args = self.cfg.strip_opts();
if let Some(strip_out) = self.strip_out.as_ref() {
if let Some(strip_out) = strip_out.try_ref() {
args.push("-o".into());
args.push(strip_out.name().clone());
}
}
args.push(out.name().clone());
let res = exec_out(&self.cfg.0.props.strip, &args).await?;
log_out!(res);
res.success()?;
}
Ok(Default::default())
}
.boxed_local()
}
}
impl CompilerConfig {
async fn compile(
self,
src: Artifact<Input, Actual>,
out_dir: Directory,
opts: Option<CompileOptions>,
) -> Result<Artifact<Input, Actual>> {
let opts = opts.unwrap_or_default();
let out_kind = opts.output;
let src_name = src.name().clone();
let in_kind = if let Some(kind) = opts.input {
kind
} else {
CInputKind::from_name(&src_name)?
};
if matches!(in_kind, CInputKind::D) {
if self.0.props.dc.is_none() {
Err(format!("No D compiler found to build `{}`", src_name))?;
}
if matches!(out_kind, COutputKind::Cpp) {
Err(format!(
"Unable preprocess `{}` because D-lang does not support C-preprocessor",
src_name
))?;
}
}
if matches!(self.0.props.kind, CompilerKind::Gcc)
&& matches!(out_kind, COutputKind::Ir | COutputKind::Bc)
{
Err(format!(
"Output intermediate reprepresentation for `{}` from GCC is experimental and does not supported yet",
src_name
))?;
}
let hash = self.hash();
let out_dir = out_dir.child(&hash);
let dst_ext = out_kind.make_extension(&src_name);
let dst_name = format!("{}.{}", src_name, dst_ext);
let dst = out_dir.output(dst_name).await?;
let dep_name = format!("{}.dep", dst.name());
let dep_path = PathBuf::from(&dep_name);
let dep_kind = if matches!(in_kind, CInputKind::D)
&& matches!(self.0.props.kind, CompilerKind::Llvm)
{
DepKind::D
} else {
DepKind::default()
};
let store: &ArtifactStore = out_dir.as_ref();
let incs = if dep_path.is_file().await {
// preload already generated deps
store
.read_deps(&dep_path, dep_kind, |src| src != &src_name)
.await?
} else {
// deps will be generated under compilation
Default::default()
};
log::debug!("Compile::new");
let rule = Ref::new(CompileInternal {
cfg: self.clone(),
store: store.clone(),
in_kind,
out_kind,
src,
dep: dep_path,
incs: Mut::new(incs),
dst: dst.weak(),
});
dst.set_rule(Rule::from_api(rule));
Ok(dst.into())
}
async fn link(
self,
objs: Set<Artifact<Input, Actual>>,
out_dir: Directory,
out_name: impl AsRef<str>,
opts: Option<LinkOptions>,
) -> Result<LinkOutput> {
let opts = opts.unwrap_or_default();
let script = opts.script;
let out_kind = opts.output;
let out_name = out_kind.file_name(&self.0.props.platform, out_name);
let out = out_dir.output(&out_name).await?;
let map_name = format!("{}.map", out_name);
let map = out_dir.output(map_name).await?;
log::debug!("Link::new");
let rule = Ref::new(LinkInternal {
cfg: self.clone(),
out_kind,
objs,
script,
out: out.weak(),
map: map.weak(),
});
let rule = Rule::from_api(rule);
out.set_rule(rule.clone());
map.set_rule(rule);
Ok(LinkOutput {
out: out.into(),
map: map.into(),
})
}
async fn strip(
self,
obj: Artifact<Input, Actual>,
out_dir: Directory,
strip_dir: Option<Directory>,
) -> Result<StripOutput> {
let obj_name = obj.name().clone();
let out_name = Path::new(&obj_name)
.file_name()
.ok_or_else(|| format!("Unable to determine file name to strip `{}`", obj_name))?
.to_str()
.unwrap();
let out = out_dir.output(out_name).await?;
let strip_out = if let Some(strip_dir) = &strip_dir {
Some(strip_dir.output(out_name).await?)
} else {
None
};
log::debug!("Strip::new");
let rule = Ref::new(StripInternal {
cfg: self.clone(),
obj,
out: out.weak(),
strip_out: strip_out.as_ref().map(|out| out.weak()),
});
let rule = Rule::from_api(rule);
if let Some(strip_out) = &strip_out {
out.set_rule(rule.clone());
strip_out.set_rule(rule);
} else {
out.set_rule(rule);
}
Ok(StripOutput {
out: out.into(),
strip: strip_out.map(|out| out.into()),
})
}
pub async fn get(&self, name: impl AsRef<str>) -> Result<String> {
let mut args = self.base_opts();
args.push(format!("-print-{}", name.as_ref()));
Ok(exec_out(&self.0.props.cc, &args)
.await?
.success()?
.out
.trim()
.into())
}
#[inline]
pub async fn sysroot(&self) -> Result<String> {
self.get("sysroot").await
}
#[inline]
pub async fn multidir(&self) -> Result<String> {
self.get("multi-directory").await
}
#[inline]
pub async fn builtins(&self) -> Result<String> {
self.get("libgcc-file-name").await
}
}
pub(super) struct LdScriptInternal {
data: LdScript,
out: WeakArtifact<Output, Actual>,
incs: Set<Artifact<Input, Actual>>,
}
impl Drop for LdScriptInternal {
fn drop(&mut self) {
log::debug!("LdScript::drop");
}
}
impl RuleApi for LdScriptInternal {
fn inputs(&self) -> Vec<Artifact<Input>> {
self.incs
.iter()
.map(|input| input.clone().into_kind_any())
.collect()
}
fn outputs(&self) -> Vec<Artifact<Output>> {
self.out
.try_ref()
.map(|input| input.into_kind_any())
.into_iter()
.collect()
}
fn invoke(self: Ref<Self>) -> BoxedFuture<Result<Diagnostics>> {
async move {
log::debug!("LdScript::invoke");
if let Some(out) = self.out.try_ref() {
let mut data = LdScript::default();
data.includes = self.incs.iter().map(|inc| inc.name().into()).collect();
let content = format!("{}{}", self.data, data);
write_file(out.name(), content).await?;
}
Ok(Default::default())
}
.boxed_local()
}
}
impl LdScriptInternal {
pub async fn create(
outdir: Directory,
name: impl AsRef<str>,
data: LdScript,
incs: Set<Artifact<Input, Actual>>,
) -> Result<Artifact<Input, Actual>> {
log::debug!("LdScript::new");
let out_name = format!("{}.ld", name.as_ref());
let out = outdir.output(out_name).await?;
let rule = Ref::new(LdScriptInternal {
data,
out: out.weak(),
incs,
});
out.set_rule(Rule::from_api(rule));
Ok(out.into())
}
}
#[derive(Debug, Clone, Default, qjs::FromJs)]
pub struct NmOptions {
/// Only debug symbols
#[quickjs(default)]
debug: bool,
/// Demangle symbols
#[quickjs(default)]
demangle: Option<String>,
/// Dynamic symbols
#[quickjs(default)]
dynamic: bool,
/// Only defined symbols
#[quickjs(default)]
defined: bool,
/// Only undefined symbols
#[quickjs(default)]
undefined: bool,
/// Only external symbols
#[quickjs(default)]
external: bool,
/// Also special symbols
#[quickjs(default)]
special: bool,
/// Also synthetic symbols
#[quickjs(default)]
synthetic: bool,
}
#[qjs::bind(module, public)]
#[quickjs(bare)]
mod js {
pub use super::*;
#[quickjs(rename = "Compiler", cloneable)]
impl CompilerConfig {
pub fn new() -> Self {
unimplemented!();
}
pub async fn detect(opts: qjs::Opt<DetectOpts>) -> Result<Self> {
let opts = opts.0.unwrap_or_default().detect().await?;
let intern = Internal::detect(opts).await?;
Ok(Self(Ref::new(intern)))
}
pub fn config(&self, opts: qjs::Opt<ToolchainOpts>) -> Result<Self> {
let opts = opts.0.unwrap_or_default();
let intern = self.0.config(opts);
Ok(Self(Ref::new(intern)))
}
#[quickjs(get, enumerable)]
pub fn cc_path(&self) -> &String {
&self.0.props.cc
}
#[quickjs(get, enumerable)]
pub fn ar_path(&self) -> &String {
&self.0.props.ar
}
#[quickjs(get, enumerable)]
pub fn nm_path(&self) -> &String {
&self.0.props.nm
}
#[quickjs(get, enumerable)]
pub fn kind(&self) -> CompilerKind {
self.0.props.kind
}
#[quickjs(get, enumerable)]
pub fn version(&self) -> &String {
&self.0.props.version
}
#[quickjs(get, enumerable)]
pub fn target(&self) -> &String {
&self.0.props.target
}
#[quickjs(rename = "options", get, enumerable)]
pub fn options_js(&self) -> ToolchainOpts {
self.0.opts.clone()
}
#[quickjs(rename = "sysroot", get, enumerable)]
pub async fn sysroot_js(self) -> Result<String> {
self.sysroot().await
}
#[quickjs(rename = "multidir", get, enumerable)]
pub async fn multidir_js(self) -> Result<String> {
self.multidir().await
}
#[quickjs(rename = "builtins", get, enumerable)]
pub async fn builtins_js(self) -> Result<String> {
self.builtins().await
}
#[quickjs(get, enumerable)]
pub async fn search_dirs(self) -> Result<Vec<String>> {
let mut args = self.base_opts();
args.push("-print-search-dirs".into());
Ok(exec_out(&self.0.props.cc, &args)
.await?
.success()?
.out
.trim()
.split(':')
.map(|path| path.into())
.collect())
}
#[quickjs(get, enumerable, hide)]
pub fn hash(&self) -> String {}
#[quickjs(get, enumerable, hide)]
pub fn c_opts(&self) -> Vec<String> {}
#[quickjs(get, enumerable, hide)]
pub fn cxx_opts(&self) -> Vec<String> {}
#[quickjs(get, enumerable, hide)]
pub fn d_opts(&self) -> Vec<String> {}
#[quickjs(get, enumerable, hide)]
pub fn link_opts(&self) -> Vec<String> {}
#[quickjs(get, enumerable, hide)]
pub fn dump_opts(&self) -> Vec<String> {}
#[quickjs(get, enumerable, hide)]
pub fn strip_opts(&self) -> Vec<String> {}
/// Compile source
#[quickjs(rename = "compile")]
pub async fn compile_js(
self,
out_dir: Directory,
src: Artifact<Input, Actual>,
opts: qjs::Opt<CompileOptions>,
) -> Result<Artifact<Input, Actual>> {
self.compile(src, out_dir, opts.0).await
}
/// Link objects
#[quickjs(rename = "link")]
pub async fn link_js(
self,
out_dir: Directory,
out_name: String,
objs: Set<Artifact<Input, Actual>>,
opts: qjs::Opt<LinkOptions>,
) -> Result<LinkOutput> {
self.link(objs, out_dir, out_name, opts.0).await
}
/// Strip objects
#[quickjs(rename = "strip")]
pub async fn strip_js(
self,
obj: Artifact<Input, Actual>,
out_dir: Directory,
strip_dir: qjs::Opt<Directory>,
) -> Result<StripOutput> {
self.strip(obj, out_dir, strip_dir.0).await
}
/// Measure size
pub async fn size(self, file: String, files: qjs::Rest<String>) -> Result<SizeInfo> {
let mut args = vec!["--format=SysV".into(), file];
args.extend(files.0);
let res = exec_out(&self.0.props.size, &args).await?;
log_out!(@err res);
res.success()?.out.parse()
}
/*
/// Extract symbols
async fn nm(self, file: String, opts: qjs::Opt<NmOptions>) -> Result<Vec<String>> {
let args = &["--print-file-name", "--print-size", "--line-numbers", ""];
let out = exec_out(&self.0.cfg.nm, args).await?.success()?.out;
}
/// Dump objects
async fn objdump(self, file: String) -> Result<String>;
*/
}
#[quickjs(rename = "LdScript")]
pub async fn ld_script(
outdir: Directory,
name: String,
opts: LdScript,
incs: qjs::Opt<Set<Artifact<Input, Actual>>>,
) -> Result<Artifact<Input, Actual>> {
LdScriptInternal::create(outdir, name, opts, incs.0.unwrap_or_default()).await
}
}
|
#[doc = "Register `PDCRI` reader"]
pub type R = crate::R<PDCRI_SPEC>;
#[doc = "Register `PDCRI` writer"]
pub type W = crate::W<PDCRI_SPEC>;
#[doc = "Field `PD0` reader - Port I pull-down bit 0"]
pub type PD0_R = crate::BitReader;
#[doc = "Field `PD0` writer - Port I pull-down bit 0"]
pub type PD0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PD1` reader - Port I pull-down bit 1"]
pub type PD1_R = crate::BitReader;
#[doc = "Field `PD1` writer - Port I pull-down bit 1"]
pub type PD1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PD2` reader - Port I pull-down bit 2"]
pub type PD2_R = crate::BitReader;
#[doc = "Field `PD2` writer - Port I pull-down bit 2"]
pub type PD2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PD3` reader - Port I pull-down bit 3"]
pub type PD3_R = crate::BitReader;
#[doc = "Field `PD3` writer - Port I pull-down bit 3"]
pub type PD3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PD4` reader - Port I pull-down bit 4"]
pub type PD4_R = crate::BitReader;
#[doc = "Field `PD4` writer - Port I pull-down bit 4"]
pub type PD4_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PD5` reader - Port I pull-down bit 5"]
pub type PD5_R = crate::BitReader;
#[doc = "Field `PD5` writer - Port I pull-down bit 5"]
pub type PD5_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PD6` reader - Port I pull-down bit 6"]
pub type PD6_R = crate::BitReader;
#[doc = "Field `PD6` writer - Port I pull-down bit 6"]
pub type PD6_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PD7` reader - Port I pull-down bit 7"]
pub type PD7_R = crate::BitReader;
#[doc = "Field `PD7` writer - Port I pull-down bit 7"]
pub type PD7_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PD8` reader - Port I pull-down bit 8"]
pub type PD8_R = crate::BitReader;
#[doc = "Field `PD8` writer - Port I pull-down bit 8"]
pub type PD8_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PD9` reader - Port I pull-down bit 9"]
pub type PD9_R = crate::BitReader;
#[doc = "Field `PD9` writer - Port I pull-down bit 9"]
pub type PD9_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PD10` reader - Port I pull-down bit 10"]
pub type PD10_R = crate::BitReader;
#[doc = "Field `PD10` writer - Port I pull-down bit 10"]
pub type PD10_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `PD11` reader - Port I pull-down bit 11"]
pub type PD11_R = crate::BitReader;
#[doc = "Field `PD11` writer - Port I pull-down bit 11"]
pub type PD11_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - Port I pull-down bit 0"]
#[inline(always)]
pub fn pd0(&self) -> PD0_R {
PD0_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - Port I pull-down bit 1"]
#[inline(always)]
pub fn pd1(&self) -> PD1_R {
PD1_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - Port I pull-down bit 2"]
#[inline(always)]
pub fn pd2(&self) -> PD2_R {
PD2_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - Port I pull-down bit 3"]
#[inline(always)]
pub fn pd3(&self) -> PD3_R {
PD3_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - Port I pull-down bit 4"]
#[inline(always)]
pub fn pd4(&self) -> PD4_R {
PD4_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - Port I pull-down bit 5"]
#[inline(always)]
pub fn pd5(&self) -> PD5_R {
PD5_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - Port I pull-down bit 6"]
#[inline(always)]
pub fn pd6(&self) -> PD6_R {
PD6_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - Port I pull-down bit 7"]
#[inline(always)]
pub fn pd7(&self) -> PD7_R {
PD7_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - Port I pull-down bit 8"]
#[inline(always)]
pub fn pd8(&self) -> PD8_R {
PD8_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - Port I pull-down bit 9"]
#[inline(always)]
pub fn pd9(&self) -> PD9_R {
PD9_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - Port I pull-down bit 10"]
#[inline(always)]
pub fn pd10(&self) -> PD10_R {
PD10_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - Port I pull-down bit 11"]
#[inline(always)]
pub fn pd11(&self) -> PD11_R {
PD11_R::new(((self.bits >> 11) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - Port I pull-down bit 0"]
#[inline(always)]
#[must_use]
pub fn pd0(&mut self) -> PD0_W<PDCRI_SPEC, 0> {
PD0_W::new(self)
}
#[doc = "Bit 1 - Port I pull-down bit 1"]
#[inline(always)]
#[must_use]
pub fn pd1(&mut self) -> PD1_W<PDCRI_SPEC, 1> {
PD1_W::new(self)
}
#[doc = "Bit 2 - Port I pull-down bit 2"]
#[inline(always)]
#[must_use]
pub fn pd2(&mut self) -> PD2_W<PDCRI_SPEC, 2> {
PD2_W::new(self)
}
#[doc = "Bit 3 - Port I pull-down bit 3"]
#[inline(always)]
#[must_use]
pub fn pd3(&mut self) -> PD3_W<PDCRI_SPEC, 3> {
PD3_W::new(self)
}
#[doc = "Bit 4 - Port I pull-down bit 4"]
#[inline(always)]
#[must_use]
pub fn pd4(&mut self) -> PD4_W<PDCRI_SPEC, 4> {
PD4_W::new(self)
}
#[doc = "Bit 5 - Port I pull-down bit 5"]
#[inline(always)]
#[must_use]
pub fn pd5(&mut self) -> PD5_W<PDCRI_SPEC, 5> {
PD5_W::new(self)
}
#[doc = "Bit 6 - Port I pull-down bit 6"]
#[inline(always)]
#[must_use]
pub fn pd6(&mut self) -> PD6_W<PDCRI_SPEC, 6> {
PD6_W::new(self)
}
#[doc = "Bit 7 - Port I pull-down bit 7"]
#[inline(always)]
#[must_use]
pub fn pd7(&mut self) -> PD7_W<PDCRI_SPEC, 7> {
PD7_W::new(self)
}
#[doc = "Bit 8 - Port I pull-down bit 8"]
#[inline(always)]
#[must_use]
pub fn pd8(&mut self) -> PD8_W<PDCRI_SPEC, 8> {
PD8_W::new(self)
}
#[doc = "Bit 9 - Port I pull-down bit 9"]
#[inline(always)]
#[must_use]
pub fn pd9(&mut self) -> PD9_W<PDCRI_SPEC, 9> {
PD9_W::new(self)
}
#[doc = "Bit 10 - Port I pull-down bit 10"]
#[inline(always)]
#[must_use]
pub fn pd10(&mut self) -> PD10_W<PDCRI_SPEC, 10> {
PD10_W::new(self)
}
#[doc = "Bit 11 - Port I pull-down bit 11"]
#[inline(always)]
#[must_use]
pub fn pd11(&mut self) -> PD11_W<PDCRI_SPEC, 11> {
PD11_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "Power Port I pull-down control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pdcri::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`pdcri::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct PDCRI_SPEC;
impl crate::RegisterSpec for PDCRI_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`pdcri::R`](R) reader structure"]
impl crate::Readable for PDCRI_SPEC {}
#[doc = "`write(|w| ..)` method takes [`pdcri::W`](W) writer structure"]
impl crate::Writable for PDCRI_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets PDCRI to value 0"]
impl crate::Resettable for PDCRI_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use regex::Regex;
use std::collections::{HashMap, HashSet};
use std::{
char::ParseCharError,
cmp::{max, min},
convert::From,
str::FromStr,
};
const WATER_SPRING: Coord = Coord { x: 500, y: 0 };
#[aoc(day17, part1)]
fn solve_part1(input: &str) -> usize {
let mut r: Reservoir = input.parse().unwrap();
r.run(WATER_SPRING);
r.count()
}
#[aoc(day17, part2)]
fn solve_part2(input: &str) -> usize {
let mut r: Reservoir = input.parse().unwrap();
r.run(WATER_SPRING);
r.rest_count()
}
#[derive(Hash, Eq, PartialEq, Debug)]
enum State {
Sand,
WetSand, // sand that water has passed through
Clay,
RestingWater,
}
#[derive(Hash, Eq, PartialEq, Copy, Clone, Debug)]
struct Coord {
x: usize,
y: usize,
}
impl From<(usize, usize)> for Coord {
fn from(t: (usize, usize)) -> Self {
Coord { x: t.0, y: t.1 }
}
}
struct Reservoir {
visited: HashSet<Coord>,
tiles: HashMap<Coord, State>,
min_y: usize,
max_y: usize,
}
impl Reservoir {
// water_start is a source of water like a water spring or the edge from an overflow
fn run(&mut self, water_start: Coord) {
// repeatedly drop water from the current position making sure to only scan
// new tiles and tiles in range
loop {
if let Some(mut c) = self.fall(water_start) {
if self.visited.contains(&c) {
break;
}
self.scan(c);
} else {
break;
}
}
}
fn scan(&mut self, c: Coord) {
self.visited.insert(c);
let (flow_left, spill_left) = self.flow_left(c);
let (flow_right, spill_right) = self.flow_right(c);
match (spill_left, spill_right) {
// no spill on either side means water can fill this area
(false, false) => {
for x in flow_left.x..=flow_right.x {
self.tiles
.insert((x, flow_left.y).into(), State::RestingWater);
}
}
(fall_left, fall_right) => {
for x in flow_left.x..=flow_right.x {
self.tiles.insert((x, flow_left.y).into(), State::WetSand);
}
if fall_left {
self.run(flow_left);
}
if fall_right {
self.run(flow_right);
}
}
}
}
fn fall(&mut self, water_start: Coord) -> Option<Coord> {
let mut curr_water = water_start;
// pour water downwards until we reach clay or resting water
while {
match self.tiles.get(&(curr_water.x, curr_water.y + 1).into()) {
None | Some(&State::WetSand) | Some(&State::Sand) => true,
Some(&State::Clay) | Some(&State::RestingWater) => false,
}
} {
curr_water.y += 1;
if curr_water.y > self.max_y {
return None;
}
self.tiles
.insert((curr_water.x, curr_water.y).into(), State::WetSand);
}
Some(curr_water)
}
fn flow_left(&mut self, mut water_start: Coord) -> (Coord, bool) {
let mut spill = false;
while {
match self.tiles.get(&(water_start.x, water_start.y + 1).into()) {
Some(State::Clay) | Some(State::RestingWater) => true,
_ => {
spill = true;
false
}
}
} {
match self.tiles.get(&(water_start.x - 1, water_start.y).into()) {
Some(State::Clay) => break,
_ => water_start.x -= 1,
}
}
(water_start, spill)
}
fn flow_right(&mut self, mut water_start: Coord) -> (Coord, bool) {
let mut spill = false;
while {
match self.tiles.get(&(water_start.x, water_start.y + 1).into()) {
Some(State::Clay) | Some(State::RestingWater) => true,
_ => {
spill = true;
false
}
}
} {
match self.tiles.get(&(water_start.x + 1, water_start.y).into()) {
Some(State::Clay) => break,
_ => water_start.x += 1,
}
}
(water_start, spill)
}
fn count(&self) -> usize {
let mut tiles_water_reached = 0;
for (c, state) in &self.tiles {
if c.y < self.min_y || c.y > self.max_y {
continue;
}
match state {
State::WetSand | State::RestingWater => tiles_water_reached += 1,
_ => (),
}
}
tiles_water_reached
}
fn rest_count(&self) -> usize {
let mut resting_water = 0;
for (c, state) in &self.tiles {
if c.y < self.min_y || c.y > self.max_y {
continue;
}
match state {
State::RestingWater => resting_water += 1,
_ => (),
}
}
resting_water
}
}
lazy_static! {
static ref x_coords: Regex = Regex::new(r"x=(?P<x>\d+), y=(?P<y>\d+\.\.\d+|\d+)").unwrap();
static ref y_coords: Regex = Regex::new(r"y=(?P<y>\d+), x=(?P<x>\d+\.\.\d+|\d+)").unwrap();
}
impl FromStr for Reservoir {
type Err = ParseCharError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut tiles = HashMap::new();
let (mut min_y, mut max_y) = (std::usize::MAX, 0);
for line in s.trim().lines() {
let line = line.trim();
if x_coords.is_match(line) {
let caps = x_coords.captures(line).unwrap();
let x_val: usize = caps["x"].parse().unwrap();
if caps["y"].contains("..") {
let mut y_range = caps["y"].split("..").map(|n| n.parse::<usize>().unwrap());
let y_start = y_range.next().unwrap();
let y_end = y_range.next().unwrap();
for n in y_start..=y_end {
min_y = min(min_y, n);
max_y = max(max_y, n);
tiles.insert((x_val, n).into(), State::Clay);
}
} else {
let y_val: usize = caps["y"].parse().unwrap();
min_y = min(min_y, y_val);
max_y = max(max_y, y_val);
tiles.insert((x_val, y_val).into(), State::Clay);
}
} else if y_coords.is_match(line) {
let caps = y_coords.captures(line).unwrap();
let y_val: usize = caps["y"].parse().unwrap();
min_y = min(min_y, y_val);
max_y = max(max_y, y_val);
if caps["x"].contains("..") {
let mut x_range = caps["x"].split("..").map(|n| n.parse::<usize>().unwrap());
let x_start = x_range.next().unwrap();
let x_end = x_range.next().unwrap();
for n in x_start..=x_end {
tiles.insert((n, y_val).into(), State::Clay);
}
} else {
let x_val = caps["x"].parse().unwrap();
tiles.insert((x_val, y_val).into(), State::Clay);
}
}
}
Ok(Reservoir {
tiles,
min_y,
max_y,
visited: HashSet::new(),
})
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn input() {
let count = solve_part1(include_str!("../input/tests/d17.txt"));
assert_eq!(count, 57);
}
}
|
use code_generator::CodeGenerator;
use syntax_analyzer::ast_node::*;
use std::env;
use std::fs::File;
use std::io::{stdin, stdout, BufRead, BufReader, BufWriter, Write};
fn main() {
let mut reader: Box<dyn BufRead> = match env::args().nth(1) {
None => Box::new(BufReader::new(stdin())),
Some(filename) => Box::new(BufReader::new(
File::open(filename).expect("cannot open file"),
)),
};
let mut writer: Box<dyn Write> = match env::args().nth(2) {
None => Box::new(BufWriter::new(stdout())),
Some(filename) => Box::new(BufWriter::new(
File::create(filename).expect("cannot create file"),
)),
};
let mut ast_str = String::new();
reader.read_to_string(&mut ast_str).expect("read error");
let ast = ASTReader::read_ast(ast_str.lines());
let code = CodeGenerator::generate(&ast).unwrap();
writer.write(code.as_bytes()).expect("write error");
}
|
#[macro_use]
extern crate log;
#[macro_use(doc, bson)]
extern crate bson;
extern crate mongo_driver;
extern crate mongo_oplog;
use bson::Bson;
use bson::oid;
use mongo_oplog::op::Op;
mod utils;
use utils::log_init;
#[test]
fn check_op_insert() {
log_init();
let insert = doc! {
"op" => "i",
"ns" => "foo.bar",
"h" => 66i64,
"ts" => (Bson::TimeStamp(0)),
"o" => {
"foo" => "bar",
"fizz" => "buzz"
}
};
let op = Op::from_doc(&insert).expect("from_doc");
match op {
Op::Insert { ref ts, ref h, ref ns, ref o } => {
assert_eq!("foo.bar", ns);
assert_eq!(&66i64, h);
assert_eq!(&0i64, ts);
assert_eq!(&doc! {
"foo" => "bar",
"fizz" => "buzz"
},
o);
}
_ => panic!("op did not match insert"),
};
}
#[test]
fn check_op_update() {
log_init();
let insert = doc! {
"op" => "u",
"ns" => "foo.bar",
"h" => 66i64,
"ts" => (Bson::TimeStamp(0)),
"o" => {
"foo" => "bar",
"fizz" => "buzz"
},
"o2" => {
"_id" => 77i32
}
};
let op = Op::from_doc(&insert).expect("from_doc");
match op {
Op::Update { ref ts, ref h, ref ns, ref o, ref o2 } => {
assert_eq!("foo.bar", ns);
assert_eq!(&66i64, h);
assert_eq!(&0i64, ts);
assert_eq!(&doc! {
"foo" => "bar",
"fizz" => "buzz"
},
o);
assert_eq!(&doc! {
"_id" => 77i32
},
o2);
}
_ => panic!("op did not match update"),
};
}
#[test]
fn check_op_noop() {
log_init();
let insert = doc! {
"op" => "n",
"h" => 66i64,
"ts" => (Bson::TimeStamp(0))
};
let op = Op::from_doc(&insert).expect("from_doc");
match op {
Op::NoOp { ref ts, ref h } => {
assert_eq!(&66i64, h);
assert_eq!(&0i64, ts);
}
_ => panic!("op did not match NoOp"),
};
}
#[test]
fn check_op_delete() {
log_init();
let id = oid::ObjectId::with_string("123456789012345678901234").unwrap();
let insert = doc! {
"op" => "d",
"ns" => "foo.bar",
"h" => 66i64,
"ts" => (Bson::TimeStamp(0)),
"o" => {
"_id" => (Bson::ObjectId(id))
}
};
let op = Op::from_doc(&insert).expect("from_doc");
match op {
Op::Delete { ref ts, ref h, ref ns, ref _id } => {
let expected_id = oid::ObjectId::with_string("123456789012345678901234").unwrap();
assert_eq!("foo.bar", ns);
assert_eq!(&66i64, h);
assert_eq!(&0i64, ts);
assert_eq!(&expected_id, _id);
}
_ => panic!("op did not match insert"),
};
}
#[test]
fn check_op_command() {
log_init();
let insert = doc! {
"op" => "c",
"h" => 66i64,
"ts" => (Bson::TimeStamp(0)),
"ns" => "test.$cmd"
};
let op = Op::from_doc(&insert).expect("from_doc");
match op {
Op::Command { ref ts, ref h, ref ns, ref o } => {
assert_eq!(&0i64, ts);
assert_eq!(&66i64, h);
assert_eq!("test.$cmd", ns);
assert!(o.is_none(), "o.is_none()");
}
_ => panic!("op did not match command"),
};
}
#[test]
fn check_op_command_apply_ops() {
log_init();
let ops: bson::Array = vec![Bson::Document(doc! {
"op" => "n",
"h" => 66i64,
"ts" => (Bson::TimeStamp(0))
})];
let insert = doc! {
"op" => "c",
"h" => 66i64,
"ts" => (Bson::TimeStamp(0)),
"ns" => "test.$cmd",
"o" => {
"applyOps" => ops
}
};
let op = Op::from_doc(&insert).expect("from_doc");
match op {
Op::ApplyOps { ts, h, ns, apply_ops } => {
assert_eq!(0i64, ts);
assert_eq!(66i64, h);
assert_eq!("test.$cmd", ns);
assert_eq!(apply_ops.len(), 1, "ops_size");
let first_op = &apply_ops[0];
match first_op {
&Op::NoOp { .. } => (),
_ => panic!("expected NoOp"),
}
}
_ => panic!("op did not match command"),
};
}
#[test]
fn check_op_unknown() {
log_init();
let insert = doc! {
"op" => "?"
};
Op::from_doc(&insert).err().expect("error expected");
}
|
use std::thread;
use std::sync::{Arc, Mutex};
struct Numero{
value: i32
}
impl Numero{
fn new(x: i32) -> Numero{
Numero{value: x}
}
fn add(& mut self, x: i32){
self.value += x;
}
fn lessthan(& self, x:i32) -> bool{
return self.value < x;
}
fn show(& self){
println!("{}", self.value);
}
}
fn main(){
}
/*fn main(){
let x = Arc::new(Mutex::new(Numero::new(0)));
let y = x.clone();
let z = x.clone();
let handler1 = thread::spawn(move || {
let mut safe_x = x.lock().unwrap();
while safe_x.lessthan(100){
safe_x.add(1);
safe_x.show();
}
});
let handler2 = thread::spawn(move || {
let mut safe_y = y.lock().unwrap();
while safe_y.lessthan(100){
safe_y.add(1);
safe_y.show();
}
});
handler1.join().unwrap();
handler2.join().unwrap();
z.lock().unwrap().show();
}*/
|
use super::Cursor;
use crate::libs::models::{Credits, Show, ShowDetails, Review};
use crate::{client, get, opt_param};
/// Show search cursor
#[derive(Clone)]
pub struct ShowSearch<'a> {
/// The url to use
url: String,
/// The handler being used to perform this search
handler: &'a Tv,
/// The current page of this search
pub page: u64,
/// The query in use
pub query: String,
/// The language that shows returned must be in
pub language: Option<String>,
/// The year that shows returned must have been first aired in
pub year: Option<String>,
/// Whether adult shows should be returned
pub adult: bool,
}
impl<'a> ShowSearch<'a> {
/// Search for shows on the currently selected page
///
/// # Examples
///
/// ```
/// pub use tmdb_cli::Client;
///
/// # #[tokio::main]
/// # async fn main() {
/// // build a client
/// let tmdb = Client::from_env();
/// // serach for a show
/// let search = tmdb.tv.search("Red Vs. Blue")
/// .language("en-us")
/// .year(2003)
/// .exec()
/// .await;
/// # assert!(search.is_ok())
/// # }
/// ```
#[syncwrap::wrap]
pub async fn exec(mut self) -> Result<Cursor<Show>, reqwest::Error> {
// cast page to a string
let adult = self.adult.to_string();
// build the url query params
let mut params: Vec<(String, String)> = Vec::with_capacity(2);
params.push(("query".into(), self.query));
params.push(("include_adult".into(), adult));
// add any optional params if they exist
opt_param!(params, "language", self.language);
opt_param!(params, "first_air_date_year", self.year);
// build cursor for this search
Cursor::new(self.url, &self.handler.token)
.page(self.page)
.params(params)
.next_page()
.await
}
/// Change the current page of our search
///
/// # Arguments
///
/// * `page` - The page to query when this search is executed
pub fn page(mut self, page: u64) -> Self {
self.page = page;
self
}
/// Sets the year shows returned from this search must have first aired in
///
/// # Arguments
///
/// * `year` - The year of release to filter on
pub fn year(mut self, year: u64) -> Self {
self.year = Some(year.to_string());
self
}
/// Sets the language that shows returned by this search must be in
///
/// # Arguments
///
/// * `lang` - The language to filter on
pub fn language<T: Into<String>>(mut self, lang: T) -> Self {
self.language = Some(lang.into());
self
}
/// Allows adult shows to be returned by this search
pub fn adult(mut self) -> Self {
self.adult = true;
self
}
}
/// Handlers for TV show focused routes
#[derive(Clone)]
pub struct Tv {
/// The URL/ip to reach tmdb at
host: String,
/// A reqwest client object
pub client: reqwest::Client,
/// A token to use when authenticating
pub token: String,
}
impl Tv {
/// Create a new TV show handler
///
/// # Arguments
///
/// * `host` - The host/url tmdb is at
/// * `token` - The token to use when authenticating
pub fn new(host: &str, token: &str) -> Self {
// build client
let client = client!();
// build shows handler
Tv {
host: host.to_owned(),
client,
token: token.to_owned(),
}
}
/// Search for a show
///
/// # Arguments
///
/// * `query` - The query to use when searching
///
/// # Examples
///
/// ```
/// pub use tmdb_cli::Client;
///
/// # #[tokio::main]
/// # async fn main() {
/// // build a client
/// let tmdb = Client::from_env();
/// // serach for a show
/// let search = tmdb.tv.search("Red Vs. Blue")
/// .year(2003)
/// .exec()
/// .await;
/// # assert!(search.is_ok())
/// # }
/// ```
pub fn search<T: Into<String>>(&self, query: T) -> ShowSearch {
ShowSearch {
url: format!("{}/3/search/tv", &self.host),
handler: self,
// start at page 1 because tmdb doesn't use 0 based indexes
page: 1,
query: query.into(),
year: None,
language: None,
adult: false,
}
}
/// Get details on a show by id
///
/// # Arguments
///
/// * `id` - The ID of the show to retrieve details on
///
/// # Examples
///
/// ```
/// pub use tmdb_cli::Client;
///
/// # #[tokio::main]
/// # async fn main() {
/// // build a client
/// let tmdb = Client::from_env();
/// // serach for a show
/// let search = tmdb.tv.details(39373).await;
/// # assert!(search.is_ok())
/// # }
/// ```
#[syncwrap::wrap]
pub async fn details(&self, id: i64) -> Result<ShowDetails, reqwest::Error> {
// build url to query
let url = format!("{}/3/tv/{}", &self.host, id);
// build a request using the our token and query
let req = self.client.get(&url).query(&[("api_key", &self.token)]);
// send request and build a ShowDetails object from the response
get!(self, req)?.json::<ShowDetails>().await
}
/// Get the credis for a show by id
///
/// # Arguments
///
/// * `id` - The ID of the show to retrieve the credits for
///
/// # Examples
///
/// ```
/// pub use tmdb_cli::Client;
///
/// # #[tokio::main]
/// # async fn main() {
/// // build a client
/// let tmdb = Client::from_env();
/// // get the credits for a show
/// let credits = tmdb.tv.credits(39373).await;
/// # assert!(credits.is_ok())
/// # }
/// ```
#[syncwrap::wrap]
pub async fn credits(&self, id: i64) -> Result<Credits, reqwest::Error> {
// build url to query
let url = format!("{}/3/tv/{}/credits", &self.host, id);
// build a request using the our token and query
let req = self.client.get(&url).query(&[("api_key", &self.token)]);
// send request and build a Credits object from the response
get!(self, req)?.json::<Credits>().await
}
/// Builds a cursor for reviews for a tv show
///
/// # Arguments
///
/// * `id` - The ID of the show to retrieve reviews for
///
/// # Examples
///
/// ```
/// pub use tmdb_cli::Client;
///
/// # #[tokio::main]
/// # async fn main() {
/// // build a client
/// let tmdb = Client::from_env();
/// // get the reviews for a show
/// let reviews = tmdb.tv.reviews(39373).exec().await;
/// # assert!(reviews.is_ok())
/// # }
/// ```
pub fn reviews(&self, id: i64) -> Cursor<Review> {
// build the url to query
let url = format!("{}/3/tv/{}/reviews", &self.host, id);
// build our cursor
Cursor::new(url, &self.token)
}
/// Builds a cursor for shows to recommend based another tv show
///
/// # Arguments
///
/// * `id` - The ID of the show to base our recommendations on
///
/// # Examples
///
/// ```
/// pub use tmdb_cli::Client;
///
/// # #[tokio::main]
/// # async fn main() {
/// // build a client
/// let tmdb = Client::from_env();
/// // get the recommendations for a show
/// let recommendations = tmdb.tv.recommendations(39373).exec().await;
/// # assert!(recommendations.is_ok())
/// # }
/// ```
pub fn recommendations(&self, id: i64) -> Cursor<Show> {
// build the url to query
let url = format!("{}/3/tv/{}/recommendations", &self.host, id);
// build our cursor
Cursor::new(url, &self.token)
}
/// Builds a cursor for shows that are similar to a tv show
///
/// This is different from the recommendation system as it looks at genres and keywords.
///
/// # Arguments
///
/// * `id` - The ID of the show to get similar shows for
///
/// # Examples
///
/// ```
/// pub use tmdb_cli::Client;
///
/// # #[tokio::main]
/// # async fn main() {
/// // build a client
/// let tmdb = Client::from_env();
/// // get shows that our similar to our show
/// let similar = tmdb.tv.similar(39373).exec().await;;
/// # assert!(similar.is_ok())
/// # }
/// ```
pub fn similar(&self, id: i64) -> Cursor<Show> {
// build the url to query
let url = format!("{}/3/tv/{}/similar", &self.host, id);
// build our cursor
Cursor::new(url, &self.token)
}
/// Builds a cursor for shows that are popular
///
/// This lists refreshes daily.
///
/// # Examples
///
/// ```
/// pub use tmdb_cli::Client;
///
/// # #[tokio::main]
/// # async fn main() {
/// // build a client
/// let tmdb = Client::from_env();
/// // get shows that are popular in the us
/// let popular = tmdb.tv.popular()
/// // you can optionally set a region to filter on
/// .param("region", "USA")
/// .exec()
/// .await;
/// # assert!(popular.is_ok())
/// # }
/// ```
pub fn popular(&self) -> Cursor<Show> {
// build the url to query
let url = format!("{}/3/tv/popular", &self.host);
Cursor::new(url, &self.token)
}
}
|
mod cd;
mod cd_query;
mod cp;
mod glob;
mod ls;
mod mkdir;
mod mv;
mod open;
mod rm;
mod save;
mod touch;
mod util;
mod watch;
pub use cd::Cd;
pub use cd_query::query;
pub use cp::Cp;
pub use glob::Glob;
pub use ls::Ls;
pub use mkdir::Mkdir;
pub use mv::Mv;
pub use open::Open;
pub use rm::Rm;
pub use save::Save;
pub use touch::Touch;
pub use util::BufferedReader;
pub use watch::Watch;
|
use crate::Result;
use clap::{App, Arg, ArgMatches};
use ronor::{Capability, HouseholdId, Player, PlayerId, Sonos};
pub const NAME: &str = "inventory";
pub fn build() -> App<'static, 'static> {
App::new(NAME)
.about("Describes available households, groups and logical players")
.arg(
Arg::with_name("AUDIO_CLIP")
.short("c")
.long("audio-clip")
.help("Limits to players with the audio-clip capability")
)
.arg(
Arg::with_name("HT_PLAYBACK")
.short("t")
.long("ht-playback")
.help("Limits to players with the home theater playback capability")
)
.arg(
Arg::with_name("LINE_IN")
.short("l")
.long("line-in")
.help("Only show players with the line-in capability")
)
.arg(
Arg::with_name("PLAYERS")
.long("players")
.help("Only show players")
)
.arg(
Arg::with_name("HOUSEHOLD")
.long("household-id")
.takes_value(true)
.value_name("IDENTIFIER")
.help("Limits output to a specific household")
)
}
pub fn run(sonos: &mut Sonos, matches: &ArgMatches) -> Result<()> {
let household_id = matches
.value_of("HOUSEHOLD")
.map(|id| HouseholdId::new(id.to_string()));
let audio_clip = if matches.is_present("AUDIO_CLIP") {
Some(Capability::AudioClip)
} else {
None
};
let ht_playback = if matches.is_present("HT_PLAYBACK") {
Some(Capability::HtPlayback)
} else {
None
};
let line_in = if matches.is_present("LINE_IN") {
Some(Capability::LineIn)
} else {
None
};
for household in sonos.get_households()?.iter().filter(|household| {
household_id
.as_ref()
.map_or(true, |household_id| household_id == &household.id)
}) {
if household_id.is_none() {
println!("Household: {}", household.id);
}
let targets = sonos.get_groups(&household)?;
fn find_player<'a>(
players: &'a [Player],
player_id: &PlayerId
) -> Option<&'a Player> {
players.iter().find(|player| &player.id == player_id)
}
if matches.is_present("PLAYERS")
|| audio_clip.is_some()
|| ht_playback.is_some()
|| line_in.is_some()
{
for player in targets
.players
.iter()
.filter(|player| {
audio_clip
.as_ref()
.map_or(true, |capability| player.capabilities.contains(&capability))
})
.filter(|player| {
ht_playback
.as_ref()
.map_or(true, |capability| player.capabilities.contains(&capability))
})
.filter(|player| {
line_in
.as_ref()
.map_or(true, |capability| player.capabilities.contains(&capability))
})
{
println!("{}", player.name);
}
} else {
for group in targets.groups.iter() {
print!("{}", group.name);
let mut player_ids = group.player_ids.iter();
if let Some(player_id) = player_ids.next() {
if let Some(player) = find_player(&targets.players, player_id) {
print!(" = {}", player.name);
for player_id in player_ids {
if let Some(player) = find_player(&targets.players, player_id) {
print!(" + {}", player.name);
}
}
}
}
println!();
}
}
}
Ok(())
}
|
/**********************************************
> File Name : most_booked.rs
> Author : lunar
> Email : lunar_ubuntu@qq.com
> Created Time : Sun Sep 4 17:16:40 2022
> Location : Shanghai
> Copyright@ https://github.com/xiaoqixian
**********************************************/
trait Comp<T> {
fn comp(&self, p2: &T) -> bool; //return true if self < p2.
}
struct PriorityQueue<T: Copy+Comp<T>> {
queue: Vec<T>,
alloc: usize //number of elements in queue
}
impl<T> PriorityQueue<T> where T: Copy+Comp<T> {
fn new() -> Self {
Self {
queue: Vec::new(),
alloc: 0
}
}
fn size(&self) -> usize {
self.alloc
}
fn empty(&self) -> bool {
self.alloc == 0
}
fn exch(&mut self, i: usize, j: usize) {
let temp = self.queue[i];
self.queue[i] = self.queue[j];
self.queue[j] = temp;
}
fn swim(&mut self, mut k: usize) {
while k > 1 && self.queue[k].comp(&self.queue[k/2]) {
self.exch(k, k/2);
k /= 2;
}
}
fn sink(&mut self, mut k: usize) -> usize {
let mut j: usize;
let size = self.alloc;
while 2*k <= size {
j = 2*k;
if j < size && self.queue[j+1].comp(&self.queue[j]) {
j += 1;
}
if !self.queue[j].comp(&self.queue[k]) {
break;
}
self.exch(j, k);
k = j;
}
k
}
fn pop(&mut self) -> Option<T> {
if self.alloc == 0 {
return None;
}
let res = Some(self.queue[1]);
self.exch(1, self.alloc);
self.alloc -= 1;
self.sink(1);
res
}
fn push(&mut self, item: T) {
if self.queue.len() == 0 {
self.queue.push(item);//queue[0] is not used.
}
if self.alloc == self.queue.len()-1 {
self.queue.push(item);
self.alloc += 1;
} else {
self.alloc += 1;
self.queue[self.alloc] = item;
}
self.swim(self.alloc);
}
}
type Room = (u64, u64, i32);
impl Comp<Room> for Room {
fn comp(&self, p2: &Room) -> bool {
if self.1 == p2.1 {
self.2 > p2.2
} else {
self.1 > p2.1
}
}
}
struct Solution;
impl Solution {
pub fn most_booked(n: i32, mut meetings: Vec<Vec<i32>>) -> i32 {
meetings.sort_by(|v1, v2| {v1[0] < v2[0]});
}
}
|
use radmin::uuid::Uuid;
use serde::{Deserialize, Serialize};
use super::ContactInfo as Contact;
use crate::models::AddressBookTag as Tag;
use crate::schema::contact_tags;
#[derive(
Debug,
PartialEq,
Clone,
Serialize,
Deserialize,
Queryable,
Identifiable,
AsChangeset,
Associations,
)]
#[belongs_to(Contact)]
#[belongs_to(Tag)]
#[table_name = "contact_tags"]
pub struct ContactTag {
pub id: Uuid,
pub contact_id: Uuid,
pub tag_id: Uuid,
}
|
//! A matrix with two rows and columns.
macro_rules! impl_op {
($op_trait:ident, $op_func:ident, $op:tt) => {
impl<I> $op_trait<I> for Mat2<I>
where I: $op_trait<I> + Copy,
<I as $op_trait<I>>::Output: Into<I>
{
type Output = Mat2<I>;
fn $op_func(mut self, other: I) -> Self::Output {
self.data[0][0] = (self.data[0][0] $op other).into();
self.data[1][0] = (self.data[1][0] $op other).into();
self.data[0][1] = (self.data[0][1] $op other).into();
self.data[1][1] = (self.data[1][1] $op other).into();
self
}
}
impl<I> $op_trait<Mat2<I>> for Mat2<I>
where I: $op_trait<I> + Copy,
<I as $op_trait<I>>::Output: Into<I>
{
type Output = Mat2<I>;
fn $op_func(mut self, other: Mat2<I>) -> Self::Output {
self.data[0][0] = (self.data[0][0] $op other.data[0][0]).into();
self.data[1][0] = (self.data[1][0] $op other.data[1][0]).into();
self.data[0][1] = (self.data[0][1] $op other.data[0][1]).into();
self.data[1][1] = (self.data[1][1] $op other.data[1][1]).into();
self
}
}
};
}
macro_rules! impl_op_ass {
($op_trait:ident, $op_func:ident, $op:tt) => {
impl<I> $op_trait<I> for Mat2<I>
where I: $op_trait<I> + Copy
{
fn $op_func(&mut self, other: I) {
self.data[0][0] $op other;
self.data[1][0] $op other;
self.data[0][1] $op other;
self.data[1][1] $op other;
}
}
impl<I> $op_trait<Mat2<I>> for Mat2<I>
where I: $op_trait<I> + Copy
{
fn $op_func(&mut self, other: Mat2<I>) {
self.data[0][0] $op other.data[0][0];
self.data[1][0] $op other.data[1][0];
self.data[0][1] $op other.data[0][1];
self.data[1][1] $op other.data[1][1];
}
}
};
}
use std::f32::consts::PI;
use super::Vec2;
use std::ops::{
Add,
Sub,
Mul,
Div,
AddAssign,
SubAssign,
MulAssign,
DivAssign,
};
use crate::serde::{Serialize, Deserialize};
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Mat2<I> {
data: [[I; 2]; 2],
}
impl<I> Mat2<I> {
pub fn new(data: [[I; 2]; 2]) -> Mat2<I> {
Mat2 {
data
}
}
pub fn from_radians(angle: f32) -> Mat2<f32> {
Mat2 {
data: [
[angle.cos(), -angle.sin()],
[angle.sin(), angle.cos()]
]
}
}
pub fn from_degrees(mut angle: f32) -> Mat2<f32> {
angle = angle/180.0 * PI;
Self::from_radians(angle)
}
pub fn as_array(self) -> [[I; 2]; 2] {
self.data
}
}
impl<I> Mul<Vec2<I>> for Mat2<I>
where I: Add<I> + Mul<I> + Copy,
<I as Mul<I>>::Output: Into<I>,
<I as Add<I>>::Output: Into<I>
{
type Output = Vec2<I>;
fn mul(self, mut other: Vec2<I>) -> Self::Output {
let x = other.x;
other.x = ((other.x * self.data[0][0]).into() + (other.y * self.data[0][1]).into()).into();
other.y = ((x * self.data[1][0]).into() + (other.y * self.data[1][1]).into()).into();
other
}
}
impl<I> Mul<Mat2<I>> for Vec2<I>
where I: Add<I> + Mul<I> + Copy,
<I as Mul<I>>::Output: Into<I>,
<I as Add<I>>::Output: Into<I>
{
type Output = Vec2<I>;
fn mul(mut self, other: Mat2<I>) -> Self::Output {
let x = self.x;
self.x = ((self.x * other.data[0][0]).into() + (self.y * other.data[0][1]).into()).into();
self.y = ((x * other.data[1][0]).into() + (self.y * other.data[1][1]).into()).into();
self
}
}
impl<I> MulAssign<Mat2<I>> for Vec2<I>
where Vec2<I>: Mul<Mat2<I>> + Clone,
<Vec2<I> as Mul<Mat2<I>>>::Output: Into<Vec2<I>>
{
fn mul_assign(&mut self, other: Mat2<I>) {
*self = (self.clone() * other).into();
}
}
impl_op!(Add, add, +);
impl_op!(Sub, sub, -);
impl_op!(Mul, mul, *);
impl_op!(Div, div, /);
impl_op_ass!(AddAssign, add_assign, +=);
impl_op_ass!(SubAssign, sub_assign, -=);
impl_op_ass!(MulAssign, mul_assign, *=);
impl_op_ass!(DivAssign, div_assign, /=);
|
// lib/option::rs
tag t<@T> { none; some(T); }
fn get<@T>(opt: t<T>) -> &T {
alt opt { some(x) { ret x; } none. { fail "option none"; } }
}
fn map<@T, @U>(f: block(T) -> U, opt: t<T>) -> t<U> {
alt opt { some(x) { some(f(x)) } none. { none } }
}
fn is_none<@T>(opt: t<T>) -> bool {
alt opt { none. { true } some(_) { false } }
}
fn is_some<@T>(opt: t<T>) -> bool { !is_none(opt) }
fn from_maybe<@T>(def: T, opt: t<T>) -> T {
alt opt { some(x) { x } none. { def } }
}
fn maybe<@T, @U>(def: U, f: block(T) -> U, opt: t<T>) -> U {
alt opt { none. { def } some(t) { f(t) } }
}
// Can be defined in terms of the above when/if we have const bind.
fn may<@T>(f: block(T), opt: t<T>) {
alt opt { none. {/* nothing */ } some(t) { f(t); } }
}
// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
|
use crate::result::{ProgramError, ProgramResult};
use prediction_poll_data::TallyData;
use solana_sdk_bpf_utils::entrypoint::SolKeyedAccount;
use solana_sdk_bpf_utils::info;
use solana_sdk_types::SolPubkey;
pub fn record_wager(
tally: &mut TallyData,
user_pubkey: &SolPubkey,
wager: u64,
) -> ProgramResult<()> {
for t in 0..*tally.len as usize {
let key = array_ref!(tally.tallies[t], 0, 32);
if key == user_pubkey {
let value_mut_ref = array_mut_ref!(tally.tallies[t], 32, 8);
let value = u64::from_be_bytes(*value_mut_ref);
*value_mut_ref = (value + wager).to_be_bytes();
return Ok(());
}
}
if (*tally.len as usize) >= tally.tallies.len() {
Err(ProgramError::MaxTallyCapacity)
} else {
let wager_bytes = wager.to_be_bytes();
for i in 0..32usize {
tally.tallies[*tally.len as usize][i] = user_pubkey[i];
}
for i in 0..8usize {
tally.tallies[*tally.len as usize][32 + i] = wager_bytes[i];
}
*tally.len += 1;
Ok(())
}
}
pub fn payout(
tally: &TallyData,
accounts: &mut [SolKeyedAccount],
winning_quantity: u64,
pot: u64,
) -> ProgramResult<()> {
if *tally.len as usize != accounts.len() {
return Err(ProgramError::CannotPayoutToSubset);
}
let mut disbursed = 0;
for index in 0..accounts.len() {
let key = *array_ref!(tally.tallies[index], 0, 32);
let value = *array_ref!(tally.tallies[index], 32, 8);
let value = u64::from_be_bytes(value);
if key != *accounts[index].key {
return Err(ProgramError::InvalidPayoutOrder);
}
let mut portion = pot * value / winning_quantity;
disbursed += portion;
if index == accounts.len() - 1 {
portion += pot - disbursed; // last voter gets the rounding error
}
info!(portion, pot, winning_quantity, *accounts[index].lamports, 0);
*accounts[index].lamports += portion;
}
Ok(())
}
|
pub mod modules {
//MODULE_JSON
pub const UNITY_2021_2_2_F_1:&str = include_str!("2021.2.2f1_modules.json");
pub const UNITY_2021_1_28_F_1:&str = include_str!("2021.1.28f1_modules.json");
}
pub mod manifests {
//MANIFEST_INI
pub const UNITY_2021_2_2_F_1:&str = include_str!("2021.2.2f1_manifest.ini");
pub const UNITY_2021_1_28_F_1:&str = include_str!("2021.1.28f1_manifest.ini");
}
|
use crate::data_lake::clients::FileSystemClient;
use crate::data_lake::responses::*;
use azure_core::prelude::*;
use azure_core::{headers::add_optional_header, AppendToUrlQuery};
use http::method::Method;
use http::status::StatusCode;
use std::convert::TryInto;
#[derive(Debug, Clone)]
pub struct DeleteFileSystemBuilder<'a> {
file_system_client: &'a FileSystemClient,
if_modified_since_condition: Option<IfModifiedSinceCondition>,
client_request_id: Option<ClientRequestId<'a>>,
timeout: Option<Timeout>,
}
impl<'a> DeleteFileSystemBuilder<'a> {
pub(crate) fn new(file_system_client: &'a FileSystemClient) -> Self {
Self {
file_system_client,
if_modified_since_condition: None,
client_request_id: None,
timeout: None,
}
}
setters! {
if_modified_since_condition: IfModifiedSinceCondition => Some(if_modified_since_condition),
client_request_id: ClientRequestId<'a> => Some(client_request_id),
timeout: Timeout => Some(timeout),
}
pub async fn execute(
&self,
) -> Result<DeleteFileSystemResponse, Box<dyn std::error::Error + Sync + Send>> {
// we clone this so we can add custom
// query parameters
let mut url = self.file_system_client.url().clone();
url.query_pairs_mut().append_pair("resource", "filesystem");
self.timeout.append_to_url_query(&mut url);
debug!("url = {}", url);
let request = self.file_system_client.prepare_request(
url.as_str(),
&Method::DELETE,
&|mut request| {
request = add_optional_header(&self.if_modified_since_condition, request);
request = add_optional_header(&self.client_request_id, request);
request
},
None,
)?;
debug!("request == {:?}", request);
let response = self
.file_system_client
.http_client()
.execute_request_check_status(request.0, StatusCode::ACCEPTED)
.await?;
Ok((&response).try_into()?)
}
}
|
// --- paritytech ---
use cumulus_pallet_dmp_queue::Config;
use frame_system::EnsureRoot;
use xcm_executor::XcmExecutor;
// --- darwinia-network ---
use crate::*;
impl Config for Runtime {
type Event = Event;
type XcmExecutor = XcmExecutor<XcmConfig>;
type ExecuteOverweightOrigin = EnsureRoot<AccountId>;
}
|
use std::iter::FromIterator;
use im::Vector;
#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct EqMap<Key: PartialEq + std::fmt::Debug + Clone, Val: std::fmt::Debug + Clone> {
storage: Vector<(Key, Val)>,
}
impl<Key: PartialEq + std::fmt::Debug + Clone, Val: std::fmt::Debug + Clone> EqMap<Key, Val> {
pub fn new() -> Self {
Self {
storage: Vector::new(),
}
}
pub fn len(&self) -> usize {
self.storage.len()
}
fn index_of(&self, key: &Key) -> Option<usize> {
for (i, (k, _)) in self.storage.iter().enumerate() {
if k == key {
return Some(i);
}
}
None
}
pub fn contains(&self, key: &Key) -> bool {
for (k, _) in self.storage.iter() {
if k == key {
return true;
}
}
false
}
pub fn get<'a>(&'a self, key: &Key) -> Option<&'a Val> {
for (k, v) in self.storage.iter() {
if k == key {
return Some(v)
}
}
None
}
pub fn update(&self, key: Key, val: Val) -> Self {
if let Some(idx) = self.index_of(&key) {
Self {
storage: self.storage.update(idx, (key, val))
}
} else {
let mut storage = self.storage.clone();
storage.push_back((key, val));
Self { storage }
}
}
}
impl<Key: PartialEq + std::fmt::Debug + Clone, Val: std::fmt::Debug + Clone> FromIterator<(Key, Val)> for EqMap<Key, Val> {
fn from_iter<T>(iter: T) -> Self
where
T : IntoIterator<Item = (Key, Val)>
{
let storage = Vector::from_iter(iter);
Self {storage}
}
}
impl<'a, Key: PartialEq + std::fmt::Debug + Clone, Val: std::fmt::Debug + Clone> IntoIterator for &'a EqMap<Key, Val> {
type Item = &'a (Key, Val);
type IntoIter = EqMapIter<'a, Key, Val>;
fn into_iter(self) -> Self::IntoIter {
EqMapIter{ eq: self, index: 0 }
}
}
pub struct EqMapIter<'a, Key: PartialEq + std::fmt::Debug + Clone, Val: std::fmt::Debug + Clone> {
eq: &'a EqMap<Key, Val>,
index: usize,
}
impl<'a, Key: PartialEq + std::fmt::Debug + Clone, Val: std::fmt::Debug + Clone> Iterator for EqMapIter<'a, Key, Val> {
type Item = &'a (Key, Val);
fn next(&mut self) -> Option<Self::Item> {
if self.index >= self.eq.len() {
None
} else {
let ret = &self.eq.storage[self.index];
self.index += 1;
Some(ret)
}
}
}
|
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio_core;
extern crate url;
mod pushover_client;
use pushover_client::PushoverClient;
fn main() {
let mut args = std::env::args().skip(1);
let key = args
.next()
.expect("pass pushover key as first positional arg");
let user = args.next().expect("pass user key as second arg");
let message = args.next().expect("pass message as third arg");
let pc = PushoverClient::from(&key);
match pc {
Ok(mut client) => {
if let Err(err) = client.push(&user, &message) {
eprintln!("{}", err)
}
}
Err(err) => eprintln!("Unable to push: {:?}", err),
}
}
|
use bip39::{Mnemonic, Language};
use sodiumoxide::crypto::hash::sha256;
use sodiumoxide::crypto::sign::ed25519;
use sodiumoxide::crypto::sign::ed25519::Seed;
#[macro_use]
extern crate clap;
fn kp(phrase: &str) {
// recover seed
let mnemonic = Mnemonic::from_phrase(phrase, Language::English).unwrap();
let seed_slice = mnemonic.entropy();
println!("Seed: {:?}", hex::encode(seed_slice));
if seed_slice.len() != 32 {
panic!("unexpected seed of length {} (expected: 32)", seed_slice.len());
}
// generate ED25519 KeyPair
let seed = Seed::from_slice(seed_slice).unwrap();
let (public, secret) = ed25519::keypair_from_seed(&seed);
// print secret- and public key
println!("Secret Key: {}", hex::encode(&secret[..]));
println!("Public Key: {}", hex::encode(&public));
}
fn hash(input: &str) {
let digest = sha256::hash(input.as_bytes());
println!("SHA256 Hash: {:?}", hex::encode(digest));
}
fn main() {
let matches = clap_app!(hesod =>
(@subcommand kp =>
(@arg MNEMONIC: +required "Sets the mnemonic to generate a ED25519 key pair from")
)
(@subcommand hash =>
(@arg INPUT: +required "input to hash")
)
).get_matches();
match matches.subcommand_name() {
Some("kp") => kp(matches.subcommand_matches("kp").unwrap().value_of("MNEMONIC").unwrap()),
Some("hash") => hash(matches.subcommand_matches("hash").unwrap().value_of("INPUT").unwrap()),
_ => panic!("unknown command triggered"),
};
}
|
use crate::exchange::trades::history::OrderBookDiff;
use crate::message::{ExchangeReply, TraderRequest};
use crate::trader::{subscriptions::{HandleSubscriptionUpdates, OrderBookSnapshot}, Trader};
use crate::types::{DateTime, StdRng};
pub struct VoidTrader;
impl HandleSubscriptionUpdates for VoidTrader {
fn handle_order_book_snapshot(&mut self, _: DateTime, _: DateTime, _: OrderBookSnapshot) -> Vec<TraderRequest> {
vec![]
}
fn handle_trade_info_update(&mut self, _: DateTime, _: DateTime, _: Vec<OrderBookDiff>) -> Vec<TraderRequest> {
vec![]
}
fn handle_wakeup(&mut self, _: DateTime) -> Vec<TraderRequest> {
vec![]
}
}
impl const Trader for VoidTrader {
fn exchange_to_trader_latency(_: &mut StdRng, _: DateTime) -> u64 { 0 }
fn trader_to_exchange_latency(_: &mut StdRng, _: DateTime) -> u64 { 0 }
fn handle_exchange_reply(&mut self, _: DateTime, _: DateTime, _: ExchangeReply) -> Vec<TraderRequest> { vec![] }
fn exchange_open(&mut self, _: DateTime, _: DateTime) {}
fn exchange_closed(&mut self, _: DateTime, _: DateTime) {}
} |
use amethyst::input::{InputBundle, StringBindings};
pub fn create_input_bundle() -> InputBundle<StringBindings> {
InputBundle::<StringBindings>::new()
} |
use std::{cmp::Ordering, collections::BTreeMap};
use chrono::{DateTime, Utc};
use futures::stream::StreamExt;
use hashbrown::HashMap;
use rosu_v2::prelude::{GameMode, User, Username};
use sqlx::Row;
use crate::{
commands::osu::UserValue,
database::{Database, UserStatsColumn, UserValueRaw},
embeds::RankingEntry,
util::constants::common_literals::USERNAME,
BotResult,
};
const COUNTRY_CODE: &str = "country_code";
type StatsValueResult<T> = BotResult<Vec<UserValueRaw<T>>>;
impl Database {
pub async fn remove_osu_user_stats(&self, user: &str) -> BotResult<()> {
let query = sqlx::query!(
"DELETE \
FROM osu_user_stats S USING osu_user_names N \
WHERE N.username ILIKE $1 \
AND S.user_id=N.user_id",
user
);
query.execute(&self.pool).await?;
let query = sqlx::query!(
"DELETE \
FROM osu_user_stats_mode S USING osu_user_names N \
WHERE N.username ILIKE $1 \
AND S.user_id=N.user_id",
user
);
query.execute(&self.pool).await?;
Ok(())
}
pub async fn get_names_by_ids(&self, ids: &[i32]) -> BotResult<HashMap<u32, Username>> {
let query = sqlx::query!(
"SELECT user_id,username from osu_user_names WHERE user_id=ANY($1)",
ids
);
let mut stream = query.fetch(&self.pool);
let mut map = HashMap::with_capacity(ids.len());
while let Some(row) = stream.next().await.transpose()? {
map.insert(row.user_id as u32, row.username.into());
}
Ok(map)
}
pub async fn get_ids_by_names(&self, names: &[String]) -> BotResult<HashMap<Username, u32>> {
let query = sqlx::query!(
"SELECT user_id,username from osu_user_names WHERE username ILIKE ANY($1)",
names
);
let mut stream = query.fetch(&self.pool);
let mut map = HashMap::with_capacity(names.len());
while let Some(row) = stream.next().await.transpose()? {
map.insert(row.username.into(), row.user_id as u32);
}
Ok(map)
}
pub async fn upsert_osu_user(&self, user: &User, mode: GameMode) -> BotResult<()> {
let mut tx = self.pool.begin().await?;
let name_query = sqlx::query!(
"INSERT INTO osu_user_names (user_id, username)\
VALUES ($1,$2) ON CONFLICT (user_id) DO \
UPDATE \
SET username=$2",
user.user_id as i32,
user.username.as_str(),
);
name_query.execute(&mut tx).await?;
let stats_query = sqlx::query!(
"INSERT INTO osu_user_stats (\
user_id,\
country_code,\
join_date,\
comment_count,\
kudosu_total,\
kudosu_available,\
forum_post_count,\
badges, played_maps,\
followers,\
graveyard_mapset_count,\
loved_mapset_count,\
mapping_followers,\
previous_usernames_count,\
ranked_mapset_count,\
medals\
)\
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16) ON CONFLICT (user_id) DO \
UPDATE \
SET country_code=$2,\
comment_count=$4,\
kudosu_total=$5,\
kudosu_available=$6,\
forum_post_count=$7,\
badges=$8,\
played_maps=$9,\
followers=$10,\
graveyard_mapset_count=$11,\
loved_mapset_count=$12,\
mapping_followers=$13,\
previous_usernames_count=$14,\
ranked_mapset_count=$15,\
medals=$16",
user.user_id as i32,
user.country_code.as_str(),
user.join_date,
user.comments_count as i32,
user.kudosu.total,
user.kudosu.available,
user.forum_post_count as i32,
user.badges.as_ref().map_or(0, Vec::len) as i32,
user.beatmap_playcounts_count.unwrap_or(0) as i32,
user.follower_count.unwrap_or(0) as i32,
user.graveyard_mapset_count.unwrap_or(0) as i32,
user.loved_mapset_count.unwrap_or(0) as i32,
user.mapping_follower_count.unwrap_or(0) as i32,
user.previous_usernames.as_ref().map_or(0, Vec::len) as i32,
user.ranked_mapset_count.unwrap_or(0) as i32,
user.medals.as_ref().map_or(0, Vec::len) as i32,
);
stats_query.execute(&mut tx).await?;
if let Some(ref stats) = user.statistics {
let mode_stats_query = sqlx::query!(
"INSERT INTO osu_user_stats_mode (\
user_id,\
mode,\
accuracy,\
pp,\
country_rank,\
global_rank,\
count_ss,\
count_ssh,\
count_s,\
count_sh,\
count_a,\
level,\
max_combo,\
playcount,\
playtime,\
ranked_score,\
replays_watched,\
total_hits,\
total_score,\
scores_first\
)\
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20) ON CONFLICT (user_id,MODE) DO \
UPDATE \
SET accuracy=$3,\
pp=$4,\
country_rank=$5,\
global_rank=$6,\
count_ss=$7,\
count_ssh=$8,\
count_s=$9,\
count_sh=$10,\
count_a=$11,\
level=$12,\
max_combo=$13,\
playcount=$14,\
playtime=$15,\
ranked_score=$16,\
replays_watched=$17,\
total_hits=$18,\
total_score=$19,\
scores_first=$20",
user.user_id as i32,
mode as i16,
stats.accuracy,
stats.pp,
stats.country_rank.unwrap_or(0) as i32,
stats.global_rank.unwrap_or(0) as i32,
stats.grade_counts.ss,
stats.grade_counts.ssh,
stats.grade_counts.s,
stats.grade_counts.sh,
stats.grade_counts.a,
stats.level.current as f32 + stats.level.progress as f32 / 100.0,
stats.max_combo as i32,
stats.playcount as i32,
stats.playtime as i32,
stats.ranked_score as i64,
stats.replays_watched as i32,
stats.total_hits as i64,
stats.total_score as i64,
user.scores_first_count.unwrap_or(0) as i32,
);
mode_stats_query.execute(&mut tx).await?;
}
Ok(tx.commit().await?)
}
pub async fn get_osu_users_stats(
&self,
column: UserStatsColumn,
discord_ids: &[i64],
) -> BotResult<BTreeMap<usize, RankingEntry>> {
let column_str = column.as_str();
match column {
UserStatsColumn::Badges
| UserStatsColumn::Comments
| UserStatsColumn::Followers
| UserStatsColumn::ForumPosts
| UserStatsColumn::GraveyardMapsets
| UserStatsColumn::JoinDate
| UserStatsColumn::KudosuAvailable
| UserStatsColumn::KudosuTotal
| UserStatsColumn::LovedMapsets
| UserStatsColumn::MappingFollowers
| UserStatsColumn::Medals
| UserStatsColumn::PlayedMaps
| UserStatsColumn::RankedMapsets
| UserStatsColumn::Usernames => {
let query = format!(
"SELECT username,{column_str},country_code \
FROM\
(SELECT osu_id \
FROM user_configs \
WHERE discord_id=ANY($1) \
AND osu_id IS NOT NULL) AS configs \
JOIN osu_user_names AS names ON configs.osu_id = names.user_id \
JOIN\
(SELECT user_id,{column_str},country_code \
FROM osu_user_stats) AS stats ON names.user_id=stats.user_id"
);
if matches!(column, UserStatsColumn::JoinDate) {
self.stats_date(&query, column_str, discord_ids)
.await
.map(|mut values| {
values.sort_unstable_by(|v1, v2| {
v1.value
.cmp(&v2.value)
.then_with(|| v1.username.cmp(&v2.username))
});
values.dedup_by(|a, b| a.username == b.username);
values
.into_iter()
.map(|v| RankingEntry {
value: UserValue::Date(v.value),
name: v.username,
country: v.country_code,
})
.enumerate()
.collect()
})
} else {
self.stats_u32(&query, column_str, discord_ids)
.await
.map(|mut values| {
values.sort_unstable_by(|v1, v2| {
v2.value
.cmp(&v1.value)
.then_with(|| v1.username.cmp(&v2.username))
});
values.dedup_by(|a, b| a.username == b.username);
values
.into_iter()
.map(|v| RankingEntry {
value: UserValue::Amount(v.value as u64),
name: v.username,
country: v.country_code,
})
.enumerate()
.collect()
})
}
}
UserStatsColumn::Accuracy { mode }
| UserStatsColumn::CountSsh { mode }
| UserStatsColumn::CountSs { mode }
| UserStatsColumn::CountSh { mode }
| UserStatsColumn::CountS { mode }
| UserStatsColumn::CountA { mode }
| UserStatsColumn::Level { mode }
| UserStatsColumn::MaxCombo { mode }
| UserStatsColumn::Playcount { mode }
| UserStatsColumn::Playtime { mode }
| UserStatsColumn::Pp { mode }
| UserStatsColumn::RankCountry { mode }
| UserStatsColumn::RankGlobal { mode }
| UserStatsColumn::Replays { mode }
| UserStatsColumn::ScoreRanked { mode }
| UserStatsColumn::ScoreTotal { mode }
| UserStatsColumn::ScoresFirst { mode }
| UserStatsColumn::TotalHits { mode } => {
let query = format!(
"SELECT username,{column_str},country_code \
FROM\
(SELECT osu_id \
FROM user_configs \
WHERE discord_id=ANY($1) \
AND osu_id IS NOT NULL) AS configs \
JOIN osu_user_names AS names ON configs.osu_id = names.user_id \
JOIN\
(SELECT user_id,{column_str} \
FROM osu_user_stats_mode \
WHERE mode={mode}) AS stats_mode ON names.user_id=stats_mode.user_id \
JOIN \
(SELECT user_id,\
country_code \
FROM osu_user_stats) AS stats ON names.user_id=stats.user_id",
mode = mode as u8
);
match column {
UserStatsColumn::Accuracy { .. } => self
.stats_f32(&query, column_str, discord_ids)
.await
.map(|mut values| {
values.sort_unstable_by(|v1, v2| {
v2.value
.partial_cmp(&v1.value)
.unwrap_or(Ordering::Equal)
.then_with(|| v1.username.cmp(&v2.username))
});
values.dedup_by(|a, b| a.username == b.username);
values
.into_iter()
.map(|v| RankingEntry {
value: UserValue::Accuracy(v.value),
name: v.username,
country: v.country_code,
})
.enumerate()
.collect()
}),
UserStatsColumn::Level { .. } => self
.stats_f32(&query, column_str, discord_ids)
.await
.map(|mut values| {
values.sort_unstable_by(|v1, v2| {
v2.value
.partial_cmp(&v1.value)
.unwrap_or(Ordering::Equal)
.then_with(|| v1.username.cmp(&v2.username))
});
values.dedup_by(|a, b| a.username == b.username);
values
.into_iter()
.map(|v| RankingEntry {
value: UserValue::Float(v.value),
name: v.username,
country: v.country_code,
})
.enumerate()
.collect()
}),
UserStatsColumn::Playtime { .. } => self
.stats_u32(&query, column_str, discord_ids)
.await
.map(|mut values| {
values.sort_unstable_by(|v1, v2| {
v2.value
.cmp(&v1.value)
.then_with(|| v1.username.cmp(&v2.username))
});
values.dedup_by(|a, b| a.username == b.username);
values
.into_iter()
.map(|v| RankingEntry {
value: UserValue::Playtime(v.value),
name: v.username,
country: v.country_code,
})
.enumerate()
.collect()
}),
UserStatsColumn::Pp { .. } => self
.stats_f32(&query, column_str, discord_ids)
.await
.map(|mut values| {
values.sort_unstable_by(|v1, v2| {
v2.value
.partial_cmp(&v1.value)
.unwrap_or(Ordering::Equal)
.then_with(|| v1.username.cmp(&v2.username))
});
values.dedup_by(|a, b| a.username == b.username);
values
.into_iter()
.map(|v| RankingEntry {
value: UserValue::PpF32(v.value),
name: v.username,
country: v.country_code,
})
.enumerate()
.collect()
}),
UserStatsColumn::RankCountry { .. } | UserStatsColumn::RankGlobal { .. } => {
self.stats_u32(&query, column_str, discord_ids)
.await
.map(|mut values| {
// Filter out inactive players
values.retain(|v| v.value != 0);
values.sort_unstable_by(|v1, v2| {
v1.value
.cmp(&v2.value)
.then_with(|| v1.username.cmp(&v2.username))
});
values.dedup_by(|a, b| a.username == b.username);
values
.into_iter()
.map(|v| RankingEntry {
value: UserValue::Rank(v.value),
name: v.username,
country: v.country_code,
})
.enumerate()
.collect()
})
}
UserStatsColumn::CountSsh { .. }
| UserStatsColumn::CountSs { .. }
| UserStatsColumn::CountSh { .. }
| UserStatsColumn::CountS { .. }
| UserStatsColumn::CountA { .. } => self
.stats_i32(&query, column_str, discord_ids)
.await
.map(|mut values| {
values.sort_unstable_by(|v1, v2| {
v2.value
.cmp(&v1.value)
.then_with(|| v1.username.cmp(&v2.username))
});
values.dedup_by(|a, b| a.username == b.username);
values
.into_iter()
.map(|v| RankingEntry {
value: UserValue::AmountWithNegative(v.value as i64),
name: v.username,
country: v.country_code,
})
.enumerate()
.collect()
}),
UserStatsColumn::MaxCombo { .. }
| UserStatsColumn::Playcount { .. }
| UserStatsColumn::Replays { .. }
| UserStatsColumn::ScoresFirst { .. } => self
.stats_u32(&query, column_str, discord_ids)
.await
.map(|mut values| {
values.sort_unstable_by(|v1, v2| {
v2.value
.cmp(&v1.value)
.then_with(|| v1.username.cmp(&v2.username))
});
values.dedup_by(|a, b| a.username == b.username);
values
.into_iter()
.map(|v| RankingEntry {
value: UserValue::Amount(v.value as u64),
name: v.username,
country: v.country_code,
})
.enumerate()
.collect()
}),
UserStatsColumn::ScoreRanked { .. }
| UserStatsColumn::ScoreTotal { .. }
| UserStatsColumn::TotalHits { .. } => self
.stats_u64(&query, column_str, discord_ids)
.await
.map(|mut values| {
values.sort_unstable_by(|v1, v2| {
v2.value
.cmp(&v1.value)
.then_with(|| v1.username.cmp(&v2.username))
});
values.dedup_by(|a, b| a.username == b.username);
values
.into_iter()
.map(|v| RankingEntry {
value: UserValue::Amount(v.value),
name: v.username,
country: v.country_code,
})
.enumerate()
.collect()
}),
_ => unreachable!(),
}
}
UserStatsColumn::AverageHits { mode } => {
let query = sqlx::query!(
"SELECT username,total_hits,playcount,country_code \
FROM\
(SELECT osu_id \
FROM user_configs \
WHERE discord_id=ANY($1) \
AND osu_id IS NOT NULL) AS configs \
JOIN osu_user_names AS names ON configs.osu_id = names.user_id \
JOIN\
(SELECT user_id,total_hits,playcount \
FROM osu_user_stats_mode \
WHERE mode=$2) AS stats_mode ON names.user_id=stats_mode.user_id \
JOIN \
(SELECT user_id,\
country_code \
FROM osu_user_stats) AS stats ON names.user_id=stats.user_id",
discord_ids,
mode as i16,
);
let mut stream = query.fetch(&self.pool);
let mut users = Vec::with_capacity(discord_ids.len());
while let Some(row) = stream.next().await.transpose()? {
let value = UserValueRaw {
username: row.username.into(),
country_code: row.country_code.into(),
value: row.total_hits as f32 / row.playcount as f32,
};
users.push(value);
}
users.sort_unstable_by(|v1, v2| {
v2.value
.partial_cmp(&v1.value)
.unwrap_or(Ordering::Equal)
.then_with(|| v1.username.cmp(&v2.username))
});
users.dedup_by(|a, b| a.username == b.username);
let values = users
.into_iter()
.map(|v| RankingEntry {
value: UserValue::Float(v.value),
name: v.username,
country: v.country_code,
})
.enumerate()
.collect();
Ok(values)
}
}
}
async fn stats_u32(
&self,
query: &str,
column: &str,
discord_ids: &[i64],
) -> StatsValueResult<u32> {
let mut stream = sqlx::query(query).bind(discord_ids).fetch(&self.pool);
let mut users = Vec::with_capacity(discord_ids.len());
while let Some(row) = stream.next().await.transpose()? {
let value = UserValueRaw {
username: row.get::<&str, _>(USERNAME).into(),
country_code: row.get::<&str, _>(COUNTRY_CODE).into(),
value: row.get::<i32, _>(column) as u32,
};
users.push(value);
}
Ok(users)
}
async fn stats_u64(
&self,
query: &str,
column: &str,
discord_ids: &[i64],
) -> StatsValueResult<u64> {
let mut stream = sqlx::query(query).bind(discord_ids).fetch(&self.pool);
let mut users = Vec::with_capacity(discord_ids.len());
while let Some(row) = stream.next().await.transpose()? {
let value = UserValueRaw {
username: row.get::<&str, _>(USERNAME).into(),
country_code: row.get::<&str, _>(COUNTRY_CODE).into(),
value: row.get::<i64, _>(column) as u64,
};
users.push(value);
}
Ok(users)
}
async fn stats_i32(
&self,
query: &str,
column: &str,
discord_ids: &[i64],
) -> StatsValueResult<i32> {
let mut stream = sqlx::query(query).bind(discord_ids).fetch(&self.pool);
let mut users = Vec::with_capacity(discord_ids.len());
while let Some(row) = stream.next().await.transpose()? {
let value = UserValueRaw {
username: row.get::<&str, _>(USERNAME).into(),
country_code: row.get::<&str, _>(COUNTRY_CODE).into(),
value: row.get(column),
};
users.push(value);
}
Ok(users)
}
async fn stats_f32(
&self,
query: &str,
column: &str,
discord_ids: &[i64],
) -> StatsValueResult<f32> {
let mut stream = sqlx::query(query).bind(discord_ids).fetch(&self.pool);
let mut users = Vec::with_capacity(discord_ids.len());
while let Some(row) = stream.next().await.transpose()? {
let value = UserValueRaw {
username: row.get::<&str, _>(USERNAME).into(),
country_code: row.get::<&str, _>(COUNTRY_CODE).into(),
value: row.get(column),
};
users.push(value);
}
Ok(users)
}
async fn stats_date(
&self,
query: &str,
column: &str,
discord_ids: &[i64],
) -> StatsValueResult<DateTime<Utc>> {
let mut stream = sqlx::query(query).bind(discord_ids).fetch(&self.pool);
let mut users = Vec::with_capacity(discord_ids.len());
while let Some(row) = stream.next().await.transpose()? {
let value = UserValueRaw {
username: row.get::<&str, _>(USERNAME).into(),
country_code: row.get::<&str, _>(COUNTRY_CODE).into(),
value: row.get(column),
};
users.push(value);
}
Ok(users)
}
}
|
extern "C" {
pub fn foo() -> i32;
pub fn bar1() -> i32;
pub fn bar2() -> i32;
pub fn asm() -> i32;
pub fn baz() -> i32;
#[cfg(windows)]
pub fn windows();
#[cfg(target_env = "msvc")]
pub fn msvc();
}
|
// Do not pop up cmd.exe window when clicking .exe on Windows. This also disables any console outputs
// so logger output will not work.
// https://learn.microsoft.com/en-us/cpp/build/reference/subsystem-specify-subsystem
#![cfg_attr(all(windows, not(debug_assertions), not(__bench)), windows_subsystem = "windows")]
use anyhow::Result;
use log::LevelFilter;
use shiba_preview::{run, Options};
use std::env;
fn main() -> Result<()> {
// When windows_subsystem is set to "windows", console outputs are detached from the process and no longer printed
// on terminal. However we still want to see the logger output for debugging by running this binary from terminal.
#[cfg(all(windows, not(debug_assertions), not(__bench)))]
let _console = shiba_preview::WindowsConsole::attach();
let Some(options) = Options::from_args(env::args().skip(1))? else { return Ok(()) };
let level = if options.debug { LevelFilter::Debug } else { LevelFilter::Info };
env_logger::builder()
.filter_level(level)
.format_timestamp(None)
.filter_module("html5ever", LevelFilter::Off)
.init();
run(options)
}
|
#[allow(unused_imports)]
use super::prelude::*;
type Input = Layout;
#[derive(PartialEq, Eq, Hash, Clone, Copy)]
pub struct Layout { layout: u32 }
impl Layout {
fn new() -> Self { Self { layout: 0 } }
fn get(&self, x: usize, y: usize) -> Tile {
if self.layout & (1 << (x + 5 * y)) != 0 { Tile::Bug } else { Tile::Empty }
}
fn set(&mut self, x: usize, y: usize, new_tile: Tile) {
match new_tile {
Tile::Bug => self.layout = self.layout | (1 << (x + 5 * y)),
Tile::Empty => self.layout = self.layout & !(1 << (x + 5 * y)),
}
}
fn count_near_bugs(&self, x: usize, y: usize) -> usize {
[(1, 0), (-1, 0), (0, 1), (0, -1)].iter().cloned()
.map(|(dx, dy)| (x as isize + dx, y as isize + dy))
.filter(|&(nx, ny)| nx >= 0 && nx < 5 && ny >= 0 && ny < 5)
.map(|(nx, ny)| (nx as usize, ny as usize))
.filter(|&(nx, ny)| self.get(nx, ny) == Tile::Bug)
.count()
}
fn biodiversity(&self) -> u32 { self.layout }
fn is_empty(&self) -> bool { self.layout == 0 }
fn count(&self) -> u32 { self.layout.count_ones() }
}
#[derive(PartialEq, Eq)]
enum Tile { Bug, Empty }
pub fn input_generator(input: &str) -> Input {
let mut layout = Layout::new();
for (y, line) in input.lines().enumerate() {
if y >= 5 { panic!("Too much lines in input") }
for (x, c) in line.chars().enumerate() {
if x >= 5 { panic!("Too much chars in line") }
layout.set(x, y, match c {
'#' => Tile::Bug,
'.' => Tile::Empty,
_ => panic!("Invalid char in input")
})
}
}
layout
}
pub fn part1(input: &Input) -> u32 {
let mut layout = *input;
let mut seen = HashSet::new();
while seen.insert(layout) {
let mut new_layout = Layout::new();
for (x, y) in (0..5).flat_map(|x| (0..5).map(move |y| (x,y))) {
let count_near = layout.count_near_bugs(x, y);
match layout.get(x, y) {
Tile::Bug if count_near == 1 => new_layout.set(x, y, Tile::Bug),
Tile::Empty if count_near == 1 || count_near == 2 => new_layout.set(x, y, Tile::Bug),
_ => {}
}
}
layout = new_layout;
}
layout.biodiversity()
}
pub fn part2(input: &Input) -> u32 {
let layout = *input;
let mut layouts = VecDeque::with_capacity(403);
let mut new_layouts = VecDeque::with_capacity(403);
layouts.push_back(layout);
layouts.push_front(Layout::new());
layouts.push_back(Layout::new());
for _ in 0..200 {
if !layouts[1].is_empty() { layouts.push_front(Layout::new()); }
if !layouts[layouts.len() - 2].is_empty() { layouts.push_back(Layout::new()); }
new_layouts.clear();
new_layouts.extend((0..layouts.len()).map(|_| Layout::new()));
for (x, y, depth) in (0..5)
.flat_map(|x| (0..5).map(move |y| (x, y)))
.flat_map(|(x, y)| (1..layouts.len()-1).map(move |d| (x, y, d)))
.filter(|&(x, y, _)| !(x == 2 && y == 2))
{
let count_near = layouts[depth].count_near_bugs(x, y)
+ if x == 0 { (layouts[depth - 1].get(1, 2) == Tile::Bug) as usize } else { 0 }
+ if x == 4 { (layouts[depth - 1].get(3, 2) == Tile::Bug) as usize } else { 0 }
+ if y == 0 { (layouts[depth - 1].get(2, 1) == Tile::Bug) as usize } else { 0 }
+ if y == 4 { (layouts[depth - 1].get(2, 3) == Tile::Bug) as usize } else { 0 }
+ match (x, y) {
(1, 2) => (0..5).filter(|&y| layouts[depth + 1].get(0, y) == Tile::Bug).count(),
(3, 2) => (0..5).filter(|&y| layouts[depth + 1].get(4, y) == Tile::Bug).count(),
(2, 1) => (0..5).filter(|&x| layouts[depth + 1].get(x, 0) == Tile::Bug).count(),
(2, 3) => (0..5).filter(|&x| layouts[depth + 1].get(x, 4) == Tile::Bug).count(),
_ => 0,
};
match layouts[depth].get(x, y) {
Tile::Bug if count_near == 1 => new_layouts[depth].set(x, y, Tile::Bug),
Tile::Empty if count_near == 1 || count_near == 2 => new_layouts[depth].set(x, y, Tile::Bug),
_ => {},
}
}
std::mem::swap(&mut layouts, &mut new_layouts);
}
layouts.iter().map(|layout| layout.count()).sum()
}
|
struct Metrolpolis{
} |
use pdb::{FallibleIterator, PdbInternalRva, PdbInternalSectionOffset, Rva};
// This test is intended to cover OMAP address translation:
// https://github.com/willglynn/pdb/issues/17
fn open_file() -> std::fs::File {
let path = "fixtures/symbol_server/3844dbb920174967be7aa4a2c20430fa2-ntkrnlmp.pdb";
std::fs::File::open(path).expect("missing fixtures, please run scripts/download from the root")
}
#[test]
fn test_omap_section_zero() {
// https://github.com/willglynn/pdb/issues/87
let mut pdb = pdb::PDB::open(open_file()).expect("opening pdb");
let address = pdb::PdbInternalSectionOffset {
offset: 0,
section: 0x1234,
};
let address_map = pdb.address_map().expect("address map");
assert_eq!(address.to_rva(&address_map), None);
}
#[test]
fn test_omap_symbol() {
let mut pdb = pdb::PDB::open(open_file()).expect("opening pdb");
let global_symbols = pdb.global_symbols().expect("global_symbols");
// find the target symbol
let target_symbol = {
let target_name = pdb::RawString::from("NtWaitForSingleObject");
let mut iter = global_symbols.iter();
iter.find(|sym| {
let matches = sym
.parse()
.ok()
.and_then(|d| d.name())
.map_or(false, |n| n == target_name);
Ok(matches)
})
.expect("iterate symbols")
.expect("find target symbol")
};
// extract the PublicSymbol data
let pubsym = match target_symbol.parse().expect("parse symbol") {
pdb::SymbolData::Public(pubsym) => pubsym,
_ => panic!("expected public symbol"),
};
// ensure the symbol has the correct location
assert_eq!(
pubsym.offset,
PdbInternalSectionOffset {
section: 0xc,
offset: 0x0004_aeb0,
}
);
// translate the segment offset to an RVA
let address_map = pdb.address_map().expect("address map");
assert_eq!(pubsym.offset.to_rva(&address_map), Some(Rva(0x0037_68c0)));
assert_eq!(
Rva(0x0037_68c0).to_internal_offset(&address_map),
Some(pubsym.offset)
);
}
#[test]
fn test_omap_range() {
let mut pdb = pdb::PDB::open(open_file()).expect("opening pdb");
let address_map = pdb.address_map().expect("address map");
// Range partially covered by OMAPs
// [
// OMAPRecord {
// source_address: 0x000010aa,
// target_address: 0x00015de6
// },
// OMAPRecord {
// source_address: 0x000010bd,
// target_address: 0x00000000
// },
// OMAPRecord {
// source_address: 0x000010c4,
// target_address: 0x0002da00
// },
// OMAPRecord {
// source_address: 0x000010c8,
// target_address: 0x0002da04
// },
// ]
let start = PdbInternalRva(0x10b0);
let end = PdbInternalRva(0x10c6);
assert_eq!(
address_map.rva_ranges(start..end).collect::<Vec<_>>(),
vec![
Rva(0x15dec)..Rva(0x15df9), // 0x10aa - 0x10bd
// 0x10bd - 0x10c4 omitted due to missing target address
Rva(0x2da00)..Rva(0x2da02), // 0x10c4 - 0x10c6
],
);
// Range starting outside OMAPs
// [
// OMAPRecord {
// source_address: 0x00001000,
// target_address: 0x00000000
// },
// OMAPRecord {
// source_address: 0x00001008,
// target_address: 0x00015d44
// },
// ]
let start = PdbInternalRva(0x0);
let end = PdbInternalRva(0x1010);
assert_eq!(
address_map.rva_ranges(start..end).collect::<Vec<_>>(),
vec![Rva(0x15d44)..Rva(0x15d4c)],
);
// Range ending outside OMAPs
// [
// OMAPRecord {
// source_address: 0x005e40e0,
// target_address: 0x005e50e0
// },
// OMAPRecord {
// source_address: 0x005e5000,
// target_address: 0x00000000
// },
// OMAPRecord {
// source_address: 0x005e70c0,
// target_address: 0x00000000
// }
// ]
let start = PdbInternalRva(0x5e_4fe0);
let end = PdbInternalRva(0x5e_8000);
assert_eq!(
address_map.rva_ranges(start..end).collect::<Vec<_>>(),
vec![Rva(0x005e_5fe0)..Rva(0x5e_6000)],
);
// Range fully before OMAPs
let start = PdbInternalRva(0x0);
let end = PdbInternalRva(0x100);
assert_eq!(
address_map.rva_ranges(start..end).collect::<Vec<_>>(),
vec![],
);
// Range fully after OMAPs
let start = PdbInternalRva(0x005e_8000);
let end = PdbInternalRva(0x005e_9000);
assert_eq!(
address_map.rva_ranges(start..end).collect::<Vec<_>>(),
vec![], // last record targets 0, thus the range is omitted
);
}
|
#![no_main]
#![no_std]
extern crate cortex_m_rt as rt;
use rt::entry;
use rt::exception;
use rt::ExceptionFrame;
extern crate cortex_m as cm;
extern crate cortex_m_semihosting;
use cortex_m_semihosting::hprintln;
extern crate panic_semihosting;
extern crate stm32f0;
use stm32f0::stm32f0x0;
#[entry]
fn main() -> ! {
let peripherals = stm32f0x0::Peripherals::take().unwrap();
let gpioa = &peripherals.GPIOA;
let rcc = &peripherals.RCC;
// enable GPIOA peripheral clock
rcc.ahbenr.write(|w| w.iopaen().set_bit());
// configure PA5 as output pin
gpioa.moder.write(|w| w.moder5().output());
// configure PA5 pin as pull-down
gpioa.pupdr.write(|w| w.pupdr5().pull_down());
loop {
hprintln!("Hello World!").unwrap();
gpioa.odr.write(|w| w.odr5().set_bit());
delay(3000);
gpioa.odr.write(|w| w.odr5().clear_bit());
delay(1000);
}
}
fn delay(count: u32) {
for _ in 0..count {
cm::asm::nop();
}
}
#[exception]
fn HardFault(ef: &ExceptionFrame) -> ! {
panic!("HardFault at {:#?}", ef);
}
#[exception]
fn DefaultHandler(irqn: i16) {
panic!("Unhandled exception (IRQn = {})", irqn);
}
|
pub mod functions;
pub mod garbage;
pub mod primitives;
pub mod strings;
pub mod vectors;
#[cfg(feature = "dataframes")]
pub mod dataframe;
pub mod series;
pub mod channels;
pub mod cells;
use crate::data::garbage::Garbage;
use comet::gc_base::GcBase;
use dyn_clone::DynClone;
use std::fmt::Debug;
use std::hash::Hash;
use crate::prelude::*;
pub trait Concrete {
type Abstract;
}
pub trait Abstract {
type Concrete;
}
pub trait DynSendable: AsyncSafe + DynClone {
type T: Sharable;
fn into_sharable(&self, ctx: Context) -> Self::T;
}
pub trait DynSharable: AsyncSafe + DynClone + Garbage + Debug {
type T: Sendable;
fn into_sendable(&self, ctx: Context) -> Self::T;
}
pub trait AsyncSafe: Send + Sync + Unpin {}
impl<T> AsyncSafe for T where T: Send + Sync + Unpin {}
pub trait Sendable: Sized + DynSendable + Clone + Serialize + DeserializeOwned {}
pub trait Sharable: Sized + DynSharable + Clone {}
pub trait DataItem: Sized + Copy + Debug + AsyncSafe {}
impl<T> Sharable for T where T: Sized + DynSharable + Clone {}
impl<T> Sendable for T where T: Sized + DynSendable + Clone + Serialize + DeserializeOwned {}
impl<T> DataItem for T where T: Sized + Copy + Debug + AsyncSafe {}
dyn_clone::clone_trait_object!(<T> DynSharable<T = T>);
dyn_clone::clone_trait_object!(<T> DynSendable<T = T>);
#[macro_export]
macro_rules! convert_reflexive {
{$({$($impl_generics:tt)+})* $ty:ty $({$($where_clause:tt)+})*} => {
impl $(<$($impl_generics)+>)* DynSharable for $ty $($($where_clause)+)* {
type T = Self;
fn into_sendable(&self, _: Context) -> Self { self.clone() }
}
impl $(<$($impl_generics)+>)* DynSendable for $ty $($($where_clause)+)* {
type T = Self;
fn into_sharable(&self, _: Context) -> Self { self.clone() }
}
}
}
pub use convert_reflexive;
|
#![allow(non_snake_case)]
mod cli;
mod task;
use structopt::StructOpt;
use cli::{Action::*, CommandLineArgs};
use task::Task;
fn main() -> std::io::Result<()> {
let CommandLineArgs { action, file } = CommandLineArgs::from_args();
let file = file.expect("Failed to find To-Do List ");
match action {
Add { task } => task::add(file, Task::new(task)),
List => task::list(file),
Remove { position } => task::remove(file, position),
Complete { position } => task::complete(file, position),
}
.expect("Invalid action");
Ok(())
}
|
use std::fmt;
#[allow(dead_code)]
#[derive(Clone, Copy, PartialEq)]
pub struct Position {
pub lin: usize,
pub col: usize,
}
#[derive(Clone, Copy)]
pub struct Cell {
pub value: Option< u8 >,
}
impl fmt::Debug for Cell {
fn fmt( &self , formatter: &mut fmt::Formatter ) -> fmt::Result {
//write!( formatter , "[ {} ]", match self.value {
// None => String::from("_"),
// Some(v) => v.to_string(),
// } )
write!( formatter , "[ {} ]"
, self.value.map_or_else(
|| String::from("_"), // None
|v| v.to_string() ) )
}
}
#[allow(dead_code)]
impl Cell {
pub fn empty() -> Self {
Cell { value: None }
}
pub fn new(v: u8 ) -> Self {
debug_assert!( 1 <= v && v <= 9 );
Cell { value: Some( v ) }
}
pub fn has_value(&self) -> bool {
self.value.is_some()
}
pub fn set_value(&mut self, _v: u8 ) -> () {
debug_assert!( 1 <= _v && _v <= 9 );
self.value = Some( _v )
}
}
#[test]
fn test_cell_01() {
let mut cell_none = Cell::empty();
assert!( !cell_none.has_value() );
cell_none.value = match cell_none.value {
None => Some( 7 ),
Some(v) => { let new_v = v + 42; Some( new_v ) }, // would not be executed
};
assert!( cell_none.has_value() );
assert!( cell_none.value == Some(7) );
let mut cell_some = Cell::new( 5 );
assert!( cell_some.has_value() );
cell_some.value = match cell_some.has_value() {
false => Some( 42 ),
true => { let new_v = cell_some.value.unwrap() + 4; Some( new_v ) },
};
assert_eq!( cell_some.value , Some( 9 ) );
match cell_some.value.as_mut() {
None => {},
Some(v) => *v = 3,
};
assert_eq!( cell_some.value , Some( 3 ) );
}
|
const INPUT: &str = include_str!("../inputs/day_5_input");
pub fn solve() {
let mut polymer = INPUT.to_owned();
println!("Final polymer length: {}", react_polymer(&mut polymer));
}
pub fn solve_extra() {
let min_polymer = (b'a'..b'z')
.map(|x| {
let mut polymer = remove_all(x, INPUT.to_owned());
let react = react_polymer(&mut polymer);
(x, react)
})
.min_by(|a, b| a.1.cmp(&b.1))
.unwrap();
println!(
"Final best polymer length without '{}': {}",
char::from(min_polymer.0),
min_polymer.1
);
}
fn react_polymer(polymer: &mut String) -> usize {
while let Some(m) = find_reaction(polymer) {
polymer.replace_range(m..=(m + 1), "");
}
polymer.len()
}
fn find_reaction(i: &str) -> Option<usize> {
let len = i.len();
let bytes = i.as_bytes();
for x in 0..(len - 1) {
let chars = &bytes[x..=(x + 1)];
let first = chars[0];
let second = chars[1];
if first.to_ascii_uppercase() == second.to_ascii_uppercase() {
if first.is_ascii_uppercase() != second.is_ascii_uppercase() {
return Some(x);
}
}
}
None
}
fn remove_all(ch: u8, i: String) -> String {
let mut new = String::with_capacity(i.len());
for b in i.as_bytes() {
if *b != ch && b.to_ascii_lowercase() != ch {
new.push(char::from(*b));
}
}
new
}
|
//! Tools to make a given actor able to receive delayed and recurring messages.
//!
//! To apply this to a given (receiving) actor:
//! * Use [`TimedContext<Self::Message>`] as [`Actor::Context`] associated type.
//! * Such actors cannot be spawned unless wrapped, making it impossible to forget wrapping it.
//! * Wrap the actor in [`Timed`] before spawning.
//!
//! The wrapped actor will accept [`TimedMessage<M>`] with convenience conversion from `M`.
//! [`RecipientExt`] becomes available for [`Recipient<TimedMessage<M>>`]s which provides methods like
//! `send_delayed()`, `send_recurring()`.
//!
//! Once accepted by the actor, delayed and recurring messages do not occupy place in actor's
//! channel inbox, they are placed to internal queue instead. Due to the design, delayed and
//! recurring messages have always lower priority than instant messages when the actor is
//! saturated.
//!
//! See `delay_actor.rs` example for usage.
use crate::{Actor, Context, Priority, Recipient, SendError, SystemHandle};
use std::{
cmp::Ordering,
collections::BinaryHeap,
ops::Deref,
time::{Duration, Instant},
};
/// A message that can be delivered now, at certain time and optionally repeatedly.
pub enum TimedMessage<M> {
Instant { message: M },
Delayed { message: M, fire_at: Instant },
Recurring { factory: Box<dyn FnMut() -> M + Send>, fire_at: Instant, interval: Duration },
}
/// This implementation allows sending direct unwrapped messages to wrapped actors.
impl<M> From<M> for TimedMessage<M> {
fn from(message: M) -> Self {
Self::Instant { message }
}
}
/// Convenience methods for [`Recipient`]s that accept [`TimedMessage`]s.
pub trait RecipientExt<M> {
/// Send a `message` now. Convenience to wrap message in [`TimedMessage::Instant`].
fn send_now(&self, message: M) -> Result<(), SendError>;
/// Send a `message` to be delivered later at a certain instant.
fn send_timed(&self, message: M, fire_at: Instant) -> Result<(), SendError>;
/// Send a `message` to be delivered later after some time from now.
fn send_delayed(&self, message: M, delay: Duration) -> Result<(), SendError> {
self.send_timed(message, Instant::now() + delay)
}
/// Schedule sending of message at `fire_at` plus at regular `interval`s from that point on.
fn send_recurring(
&self,
factory: impl FnMut() -> M + Send + 'static,
fire_at: Instant,
interval: Duration,
) -> Result<(), SendError>;
}
impl<M> RecipientExt<M> for Recipient<TimedMessage<M>> {
fn send_now(&self, message: M) -> Result<(), SendError> {
self.send(TimedMessage::Instant { message })
}
fn send_timed(&self, message: M, fire_at: Instant) -> Result<(), SendError> {
self.send(TimedMessage::Delayed { message, fire_at })
}
fn send_recurring(
&self,
factory: impl FnMut() -> M + Send + 'static,
fire_at: Instant,
interval: Duration,
) -> Result<(), SendError> {
self.send(TimedMessage::Recurring { factory: Box::new(factory), fire_at, interval })
}
}
/// A [`Context`] variant available to actors wrapped by the [`Timed`] actor wrapper.
pub struct TimedContext<M> {
pub system_handle: SystemHandle,
pub myself: Recipient<TimedMessage<M>>,
}
impl<M> TimedContext<M> {
fn from_context(context: &Context<TimedMessage<M>>) -> Self {
TimedContext {
system_handle: context.system_handle.clone(),
myself: context.myself.clone(),
}
}
}
/// A wrapper around actors to add ability to receive delayed and recurring messages.
/// See [module documentation](self) for a complete recipe.
pub struct Timed<A: Actor> {
inner: A,
queue: BinaryHeap<QueueItem<A::Message>>,
}
impl<M: Send + 'static, A: Actor<Context = TimedContext<M>, Message = M>> Timed<A> {
pub fn new(inner: A) -> Self {
Self { inner, queue: Default::default() }
}
fn schedule_timeout(&self, context: &mut <Self as Actor>::Context) {
// Schedule next timeout if the queue is not empty.
context.set_deadline(self.queue.peek().map(|earliest| earliest.fire_at));
}
}
impl<M: Send + 'static, A: Actor<Context = TimedContext<M>, Message = M>> Actor for Timed<A> {
type Context = Context<Self::Message>;
type Error = A::Error;
type Message = TimedMessage<M>;
fn handle(
&mut self,
context: &mut Self::Context,
timed_message: Self::Message,
) -> Result<(), Self::Error> {
let item = match timed_message {
TimedMessage::Instant { message } => {
return self.inner.handle(&mut TimedContext::from_context(context), message);
},
TimedMessage::Delayed { message, fire_at } => {
QueueItem { fire_at, payload: Payload::Delayed { message } }
},
TimedMessage::Recurring { factory, fire_at, interval } => {
QueueItem { fire_at, payload: Payload::Recurring { factory, interval } }
},
};
self.queue.push(item);
self.schedule_timeout(context);
Ok(())
}
fn name() -> &'static str {
A::name()
}
fn priority(message: &Self::Message) -> Priority {
match message {
// Use underlying message priority if we can reference it.
TimedMessage::Instant { message } | TimedMessage::Delayed { message, .. } => {
A::priority(message)
},
// Recurring message is only received once, the recurring instances go through the
// internal queue (and not actor's channel). Assign high priority to the request to
// set-up the recurrent sending.
TimedMessage::Recurring { .. } => Priority::High,
}
}
fn started(&mut self, context: &mut Self::Context) {
self.inner.started(&mut TimedContext::from_context(context))
}
fn stopped(&mut self, context: &mut Self::Context) {
self.inner.stopped(&mut TimedContext::from_context(context))
}
fn deadline_passed(
&mut self,
context: &mut Self::Context,
_deadline: Instant,
) -> Result<(), Self::Error> {
// Handle all messages that should have been handled by now.
let now = Instant::now();
while self.queue.peek().map(|m| m.fire_at <= now).unwrap_or(false) {
let item = self.queue.pop().expect("heap is non-empty, we have just peeked");
let message = match item.payload {
Payload::Delayed { message } => message,
Payload::Recurring { mut factory, interval } => {
let message = factory();
self.queue.push(QueueItem {
fire_at: item.fire_at + interval,
payload: Payload::Recurring { factory, interval },
});
message
},
};
// Let inner actor do its job.
self.inner.handle(&mut TimedContext::from_context(context), message)?;
}
self.schedule_timeout(context);
Ok(())
}
}
/// Access wrapped actor.
impl<A: Actor> Deref for Timed<A> {
type Target = A;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
/// Implementation detail, element of message queue ordered by time to fire at.
struct QueueItem<M> {
fire_at: Instant,
payload: Payload<M>,
}
impl<M> PartialEq for QueueItem<M> {
fn eq(&self, other: &Self) -> bool {
self.fire_at == other.fire_at
}
}
// We cannot derive because that would add too strict bounds.
impl<M> Eq for QueueItem<M> {}
impl<M> PartialOrd for QueueItem<M> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
// Reverse because [BinaryHeap] is a *max* heap, but we want pop() to return lowest `fire_at`.
Some(self.fire_at.cmp(&other.fire_at).reverse())
}
}
impl<M> Ord for QueueItem<M> {
fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).expect("we can always compare")
}
}
enum Payload<M> {
Delayed { message: M },
Recurring { factory: Box<dyn FnMut() -> M + Send>, interval: Duration },
}
|
use components::Link;
use prelude::*;
pub fn view<T: Component>(routes: Vec<(Route, String)>, current: &str) -> Html<T> {
html! {
<nav class="breadcrumbs", >
<span class="breadcrumb_links", >
{ for routes.iter().map(|(route, label)| {
html! {
<Link:
class="breadcrumb",
route=route,
text=label,
/>
}
}) }
</span>
<span class="breadcrumb_current", >
{ current }
</span>
</nav>
}
}
|
pub mod p1;
pub mod p2;
pub mod p3;
pub struct Solution {}
|
use super::IRustError;
use crate::irust::IRust;
use crate::utils::{read_until_bytes, StringTools};
use crossterm::ClearType;
use std::env::temp_dir;
use std::io::{self, Write};
use std::process::{Child, Command, Stdio};
pub enum Cycle {
Up,
Down,
}
pub struct Racer {
process: Child,
main_file: String,
cursor: (usize, usize),
// suggestions: (Name, definition)
suggestions: Vec<(String, String)>,
suggestion_idx: usize,
cmds: [String; 8],
update_lock: bool,
}
impl Racer {
pub fn start() -> Result<Racer, IRustError> {
let process = Command::new("racer")
.arg("daemon")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
// Disable Racer if unable to start it
.map_err(|_| IRustError::RacerDisabled)?;
let main_file = temp_dir()
.join("irust/src/main.rs")
.to_str()
.unwrap()
.to_owned();
let cursor = (2, 0);
let cmds = [
"show".to_string(),
"help".to_string(),
"pop".to_string(),
"del".to_string(),
"add".to_string(),
"reset".to_string(),
"load".to_string(),
"type".to_string(),
];
let mut racer = Racer {
process,
main_file,
cursor,
suggestions: vec![],
suggestion_idx: 0,
cmds,
update_lock: false,
};
racer.complete_code()?;
Ok(racer)
}
fn complete_code(&mut self) -> io::Result<()> {
// check for lock
if self.update_lock {
return Ok(());
}
// reset suggestions
self.suggestions.clear();
self.goto_first_suggestion();
let stdin = self.process.stdin.as_mut().unwrap();
let stdout = self.process.stdout.as_mut().unwrap();
writeln!(
stdin,
"complete {} {} {}",
self.cursor.0, self.cursor.1, self.main_file
)?;
// read till END
let mut raw_output = vec![];
read_until_bytes(
&mut std::io::BufReader::new(stdout),
b"END",
&mut raw_output,
)?;
let raw_output = String::from_utf8(raw_output.to_vec()).unwrap();
for suggestion in raw_output.lines().skip(1) {
if suggestion == "END" {
break;
}
let mut try_parse = || -> Option<()> {
let start_idx = suggestion.find("MATCH ")? + 6;
let mut indices = suggestion.match_indices(',');
let name = suggestion[start_idx..indices.nth(0)?.0].to_owned();
let definition = suggestion[indices.nth(3)?.0..].to_owned();
self.suggestions.push((name, definition[1..].to_owned()));
Some(())
};
try_parse();
}
// remove duplicates
self.suggestions.sort();
self.suggestions.dedup();
Ok(())
}
fn goto_next_suggestion(&mut self) {
if self.suggestion_idx >= self.suggestions.len() {
self.suggestion_idx = 0
}
self.suggestion_idx += 1;
}
fn goto_previous_suggestion(&mut self) {
self.suggestion_idx = self
.suggestion_idx
.checked_sub(1)
.unwrap_or_else(|| self.suggestions.len());
if self.suggestion_idx == 0 {
self.suggestion_idx = self.suggestions.len();
}
}
fn current_suggestion(&self) -> Option<(String, String)> {
if self.suggestion_idx > 1 {
self.suggestions
.get(self.suggestion_idx - 1)
.map(ToOwned::to_owned)
} else {
self.suggestions.get(0).map(ToOwned::to_owned)
}
}
fn goto_first_suggestion(&mut self) {
self.suggestion_idx = 0;
}
fn full_suggestion(s: &(String, String)) -> String {
if !s.1.is_empty() {
s.0.to_owned() + ": " + &s.1
} else {
s.0.to_owned()
}
}
}
impl IRust {
pub fn update_suggestions(&mut self) -> Result<(), IRustError> {
// return if we're not at the end of the line
if !self.at_line_end() {
return Ok(());
}
// don't autocomplete shell commands
if self.buffer.starts_with("::") {
return Ok(());
}
self.show_suggestions_inner()?;
Ok(())
}
fn show_suggestions_inner(&mut self) -> Result<(), IRustError> {
if self.buffer.starts_with(':') {
// Auto complete IRust commands
self.racer.as_mut()?.suggestions = self
.racer
.as_ref()?
.cmds
.iter()
.filter(|c| c.starts_with(&self.buffer[1..]))
// place holder for IRust command definitions
.map(|c| (c.to_owned(), String::new()))
.collect();
} else {
// Auto complete rust code
let mut racer = self.racer.as_mut()?;
racer.cursor.0 = self.repl.body.len();
// add +1 for the \t
racer.cursor.1 = StringTools::chars_count(&self.buffer) + 1;
self.repl
.exec_in_tmp_repl(self.buffer.clone(), move || -> Result<(), IRustError> {
racer.complete_code().map_err(From::from)
})?;
// reset debouncer
self.debouncer.reset_timer();
}
Ok(())
}
fn write_next_suggestion(&mut self) -> Result<(), IRustError> {
self.racer.as_mut()?.goto_next_suggestion();
self.write_current_suggestion()?;
Ok(())
}
fn write_previous_suggestion(&mut self) -> Result<(), IRustError> {
self.racer.as_mut()?.goto_previous_suggestion();
self.write_current_suggestion()?;
Ok(())
}
fn write_first_suggestion(&mut self) -> Result<(), IRustError> {
self.racer.as_mut()?.goto_first_suggestion();
self.write_current_suggestion()?;
Ok(())
}
fn write_current_suggestion(&mut self) -> Result<(), IRustError> {
if let Some(suggestion) = self.racer.as_ref()?.current_suggestion() {
if self.at_line_end() {
let mut suggestion = suggestion.0;
self.color
.set_fg(self.options.racer_inline_suggestion_color)?;
self.cursor.hide()?;
self.save_cursor_position()?;
self.terminal.clear(ClearType::FromCursorDown)?;
StringTools::strings_unique(&self.buffer, &mut suggestion);
let overflow = self.screen_height_overflow_by_str(&suggestion);
self.write(&suggestion)?;
self.reset_cursor_position()?;
self.cursor.show()?;
if overflow != 0 {
self.cursor.move_up(overflow as u16);
self.internal_cursor.screen_pos.1 -= overflow;
}
self.color.reset()?;
}
}
Ok(())
}
pub fn cycle_suggestions(&mut self, cycle: Cycle) -> Result<(), IRustError> {
if self.at_line_end() {
// Clear screen from cursor down
self.terminal.clear(ClearType::FromCursorDown)?;
// No suggestions to show
if self.racer.as_ref()?.suggestions.is_empty() {
return Ok(());
}
// Write inline suggestion
match cycle {
Cycle::Down => self.write_next_suggestion()?,
Cycle::Up => self.write_previous_suggestion()?,
}
// Max suggestions number to show
let suggestions_num = std::cmp::min(
self.racer.as_ref()?.suggestions.len(),
self.options.racer_max_suggestions,
);
// Handle screen height overflow
let height_overflow = self.screen_height_overflow_by_new_lines(suggestions_num + 1);
if height_overflow != 0 {
self.scroll_up(height_overflow);
}
// Save cursors postions from this point (Input position)
self.save_cursor_position()?;
// Write from screen start if a suggestion will be truncated
let mut max_width = self.size.0 - self.internal_cursor.screen_pos.0;
if self
.racer
.as_ref()?
.suggestions
.iter()
.any(|s| Racer::full_suggestion(s).len() > max_width)
{
self.internal_cursor.screen_pos.0 = 0;
self.goto_cursor()?;
max_width = self.size.0 - self.internal_cursor.screen_pos.0;
}
// Write the suggestions
self.color
.set_fg(self.options.racer_suggestions_table_color)?;
let current_suggestion = self.racer.as_ref()?.current_suggestion();
for (idx, suggestion) in self
.racer
.as_ref()?
.suggestions
.iter()
.skip(
((self.racer.as_ref()?.suggestion_idx - 1) / suggestions_num) * suggestions_num,
)
.take(suggestions_num)
.enumerate()
{
// color selected suggestion
if Some(suggestion) == current_suggestion.as_ref() {
self.color
.set_bg(self.options.racer_selected_suggestion_color)?;
}
// trancuate long suggestions
let mut suggestion = Racer::full_suggestion(suggestion);
if suggestion.len() > max_width {
suggestion.truncate(max_width - 3);
suggestion.push_str("...");
}
// move one + idx row down
self.cursor.move_down(idx as u16 + 1);
// write suggestion
self.terminal.write(&suggestion)?;
// move back to initial position
self.cursor.move_up(idx as u16 + 1);
self.cursor.move_left(suggestion.len() as u16);
// reset color in case of current suggestion
self.color.set_bg(crossterm::Color::Reset)?;
}
// reset to input position and color
self.color.reset()?;
self.reset_cursor_position()?;
}
Ok(())
}
pub fn use_suggestion(&mut self) -> Result<(), IRustError> {
if let Some(suggestion) = self.racer.as_ref()?.current_suggestion() {
// suggestion => `name: definition`
// suggestion example => `assert!: macro_rules! assert {`
// get the name
let mut suggestion = suggestion.0;
// get the unique part of the name
StringTools::strings_unique(&self.buffer, &mut suggestion);
self.buffer.push_str(&suggestion);
self.internal_cursor.buffer_pos = StringTools::chars_count(&self.buffer);
// clear screen from cursor down
self.terminal.clear(ClearType::FromCursorDown)?;
// write the suggestion
self.write(&suggestion)?;
// Unlock racer suggestions update
let _ = self.unlock_racer_update();
}
Ok(())
}
pub fn lock_racer_update(&mut self) -> Result<(), IRustError> {
self.racer.as_mut()?.update_lock = true;
Ok(())
}
pub fn unlock_racer_update(&mut self) -> Result<(), IRustError> {
self.racer.as_mut()?.update_lock = false;
Ok(())
}
fn racer_update_locked(&mut self) -> Result<bool, IRustError> {
Ok(self.racer.as_ref()?.update_lock)
}
pub fn check_racer_callback(&mut self) -> Result<(), IRustError> {
let mut inner = || -> Result<(), IRustError> {
if let Some(character) = self.buffer.chars().last() {
if character.is_alphanumeric()
&& !self.racer_update_locked()?
&& self.debouncer.recv.try_recv().is_ok()
{
self.update_suggestions()?;
self.write_first_suggestion()?;
}
}
Ok(())
};
match inner() {
Ok(_) | Err(IRustError::RacerDisabled) => Ok(()),
Err(e) => Err(e),
}
}
}
|
pub mod shapes {
#[derive(Debug)]//basically toString functionality
pub struct Rectangle<'a, 'b> {
width: &'a i32,
height: &'b i32,
}
impl<'a, 'b> Rectangle<'a, 'b> {
pub fn area(&self) -> i32 {
self.width * self.height
}
pub fn from(width: &'a i32, height: &'b i32) -> Rectangle<'a, 'b> {
Rectangle {
width,
height,
}
}
pub fn square(size: &i32) -> Rectangle {
Rectangle {
width: size,
height: size,
}
}
}
}
pub mod functions {
use std::cmp::Ordering;
use std::fs::read;
use std::io;
use std::io::Write;
use chrono::{Datelike, Utc};
use rand::Rng;
pub fn var_fibonacci(n: i32) -> i32 {
if n == 0 || n == 1 {
return 1;
} else {
let mut a = 0;
let mut b = 1;
let mut c;
for _i in 1..n {
c = a + b;
a = b;
b = c;
}
return b;
}
}
pub fn arr_fibonacci(n: i32) -> i32 {
if n == 0 || n == 1 {
return 1;
} else {
let mut arr = vec![1; n as usize];
for i in 2..n {
let index = i as usize;
arr[index] = arr[index - 1] + arr[index - 2];
}
return arr[n as usize - 1];
}
}
pub fn math_fibonacci(n: i32) -> u64 {
let phi = (1f64 + (5f64).sqrt()) / (2f64);
return (phi.powi(n) / (5f64).sqrt()).floor() as u64;
}
pub fn guessing_game() {
let secret_number = rand::thread_rng().gen_range(1, 101);
println!("Guess the number!");
loop {
println!("Please input your guess");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue
};
println!("You guessed {}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Equal => {
println!("You win!");
break;
}
Ordering::Greater => println!("Too big!")
}
}
}
pub fn year_you_turn_100() {
const ERROR_MESSAGE: &str = "Something went wrong :(";
let name = input("What is your name?")
.expect(ERROR_MESSAGE);
let age: i32 = input("How old are you?")
.expect(ERROR_MESSAGE)
.parse()
.expect("Age invalid");
let curr_year = Utc::now().year();
let res = 100 - age + curr_year;
if age > 100 {
println!("{} turned 100 in {}", name, res);
} else {
println!("{} will turn 100 in {}", name, res);
}
}
pub fn first_word(s: &str) -> &str {
for (i, &letter) in s.as_bytes().iter().enumerate() {
if letter == b' ' {
return &s[0..i];
}
}
return &s;
}
pub fn input(message: &str) -> io::Result<String> {
print!("{} ", message);
io::stdout().flush()?;
let mut buffer: String = String::new();
io::stdin().read_line(&mut buffer)?;
return Ok(buffer.trim().to_owned());
}
pub fn to_pig_latin(input: &str) -> String {
let mut res = String::new();
for word in input.split_whitespace() {
if "aeiouAEIOU".contains(&word[0..1]) {
res = format!("{} {}-{}", res, word, "hay");
} else {
res = format!("{} {}{}{}", res, &word[1..], &word[0..1], "ay");
}
}
return res.trim().to_owned();
}
pub fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
let mut largest = list[0];
for &element in &list[1..] {
if element > largest {
largest = element;
}
}
largest
}
}
|
#[macro_export] macro_rules! or {
( $( $predicate:expr ),* ) => {
Box::new(move |chr| {
$( $predicate(chr) || )* false
})
};
}
#[macro_export] macro_rules! and {
( $( $predicate:expr ),* ) => {
Box::new(move |chr| {
$( $predicate(chr) && )* true
})
};
}
pub fn among<'a>(characters: &'a str) -> Box<dyn Fn(u8) -> bool + 'a> {
Box::new(move |chr| {
characters.chars().any(|it| it == chr as char)
})
}
pub fn range(start:u8, end:u8) -> Box<dyn Fn(u8) -> bool> {
Box::new(move |chr| {
chr >= start && chr <= end
})
}
pub fn ch(value:u8) -> Box<dyn Fn(u8) -> bool> {
Box::new(move |chr| {
chr == value
})
}
pub fn not(predicate:Box<dyn Fn(u8) -> bool>) -> Box<dyn Fn(u8) -> bool> {
Box::new(move |chr| {
!predicate(chr)
})
} |
use swf_tree as ast;
use nom::{IResult, Needed};
use nom::{le_u8 as parse_u8, le_u16 as parse_le_u16};
use parsers::basic_data_types::{
parse_bool_bits,
parse_i32_bits,
parse_u16_bits,
parse_u32_bits,
parse_le_fixed8_p8,
parse_matrix,
parse_s_rgb8,
parse_straight_s_rgba8
};
use parsers::gradient::parse_gradient;
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum ShapeVersion {
Shape1,
Shape2,
Shape3,
// Shape4,
}
pub fn parse_glyph(input: &[u8]) -> IResult<&[u8], ast::Glyph> {
bits!(input, parse_glyph_bits)
}
pub fn parse_glyph_bits(input: (&[u8], usize)) -> IResult<(&[u8], usize), ast::Glyph> {
do_parse!(
input,
fill_bits: map!(apply!(parse_u32_bits, 4), |x| x as usize) >>
line_bits: map!(apply!(parse_u32_bits, 4), |x| x as usize) >>
// TODO: Check which shape version to use
records: apply!(parse_shape_record_string_bits, fill_bits, line_bits, ShapeVersion::Shape1) >>
(ast::Glyph {
records: records,
})
)
}
pub fn parse_shape(input: &[u8], version: ShapeVersion) -> IResult<&[u8], ast::Shape> {
bits!(input, apply!(parse_shape_bits, version))
}
pub fn parse_shape_bits(input: (&[u8], usize), version: ShapeVersion) -> IResult<(&[u8], usize), ast::Shape> {
do_parse!(
input,
styles: apply!(parse_shape_styles_bits, version) >>
records: apply!(parse_shape_record_string_bits, styles.fill_bits, styles.line_bits, version) >>
(ast::Shape {
fill_styles: styles.fill,
line_styles: styles.line,
records: records,
})
)
}
pub struct ShapeStyles {
pub fill: Vec<ast::FillStyle>,
pub line: Vec<ast::LineStyle>,
pub fill_bits: usize,
pub line_bits: usize,
}
pub fn parse_shape_styles_bits(input: (&[u8], usize), version: ShapeVersion) -> IResult<(&[u8], usize), ShapeStyles> {
do_parse!(
input,
fill: bytes!(apply!(parse_fill_style_list, version)) >>
line: bytes!(apply!(parse_line_style_list, version)) >>
fill_bits: map!(apply!(parse_u32_bits, 4), |x| x as usize) >>
line_bits: map!(apply!(parse_u32_bits, 4), |x| x as usize) >>
(ShapeStyles {
fill: fill,
line: line,
fill_bits: fill_bits,
line_bits: line_bits,
})
)
}
pub fn parse_shape_record_string_bits(input: (&[u8], usize), mut fill_bits: usize, mut line_bits: usize, version: ShapeVersion) -> IResult<(&[u8], usize), Vec<ast::ShapeRecord>> {
let mut result: Vec<ast::ShapeRecord> = Vec::new();
let mut current_input = input;
loop {
match parse_u16_bits(current_input, 6) {
IResult::Done(next_input, record_head) => if record_head == 0 {
current_input = next_input;
break
},
IResult::Error(e) => return IResult::Error(e),
IResult::Incomplete(_) => return IResult::Incomplete(Needed::Unknown),
};
let is_edge = match parse_bool_bits(current_input) {
IResult::Done(next_input, is_edge) => {
current_input = next_input;
is_edge
}
IResult::Error(e) => return IResult::Error(e),
IResult::Incomplete(_) => return IResult::Incomplete(Needed::Unknown),
};
if is_edge {
let is_straight_edge = match parse_bool_bits(current_input) {
IResult::Done(next_input, is_straight_edge) => {
current_input = next_input;
is_straight_edge
}
IResult::Error(e) => return IResult::Error(e),
IResult::Incomplete(_) => return IResult::Incomplete(Needed::Unknown),
};
if is_straight_edge {
match parse_straight_edge_bits(current_input) {
IResult::Done(next_input, straight_edge) => {
let record = ast::ShapeRecord::StraightEdge(straight_edge);
result.push(record);
current_input = next_input;
}
IResult::Error(e) => return IResult::Error(e),
IResult::Incomplete(n) => return IResult::Incomplete(n),
};
} else {
match parse_curved_edge_bits(current_input) {
IResult::Done(next_input, curved_edge) => {
let record = ast::ShapeRecord::CurvedEdge(curved_edge);
result.push(record);
current_input = next_input;
}
IResult::Error(e) => return IResult::Error(e),
IResult::Incomplete(n) => return IResult::Incomplete(n),
};
}
} else {
match parse_style_change_bits(current_input, fill_bits, line_bits, version) {
IResult::Done(next_input, record_and_bits) => {
let (style_change, style_bits) = record_and_bits;
fill_bits = style_bits.0;
line_bits = style_bits.1;
let record = ast::ShapeRecord::StyleChange(style_change);
result.push(record);
current_input = next_input;
}
IResult::Error(e) => return IResult::Error(e),
IResult::Incomplete(n) => return IResult::Incomplete(n),
};
}
}
IResult::Done(current_input, result)
}
pub fn parse_curved_edge_bits(input: (&[u8], usize)) -> IResult<(&[u8], usize), ast::shape_records::CurvedEdge> {
do_parse!(
input,
n_bits: map!(apply!(parse_u16_bits, 4), |x| x as usize) >>
control_x: apply!(parse_i32_bits, n_bits + 2) >>
control_y: apply!(parse_i32_bits, n_bits + 2) >>
delta_x: apply!(parse_i32_bits, n_bits + 2) >>
delta_y: apply!(parse_i32_bits, n_bits + 2) >>
(ast::shape_records::CurvedEdge {
control_delta: ast::Vector2D {x: control_x, y: control_y},
end_delta: ast::Vector2D {x: delta_x, y: delta_y},
})
)
}
pub fn parse_straight_edge_bits(input: (&[u8], usize)) -> IResult<(&[u8], usize), ast::shape_records::StraightEdge> {
do_parse!(
input,
n_bits: map!(apply!(parse_u16_bits, 4), |x| x as usize) >>
is_diagonal: call!(parse_bool_bits) >>
is_vertical: map!(cond!(!is_diagonal, call!(parse_bool_bits)), |opt: Option<bool>| opt.unwrap_or_default()) >>
delta_x: cond!(is_diagonal || !is_vertical, apply!(parse_i32_bits, n_bits + 2)) >>
delta_y: cond!(is_diagonal || is_vertical, apply!(parse_i32_bits, n_bits + 2)) >>
(ast::shape_records::StraightEdge {
end_delta: ast::Vector2D {x: delta_x.unwrap_or_default(), y: delta_y.unwrap_or_default()},
})
)
}
pub fn parse_style_change_bits(input: (&[u8], usize), fill_bits: usize, line_bits: usize, version: ShapeVersion) -> IResult<(&[u8], usize), (ast::shape_records::StyleChange, (usize, usize))> {
do_parse!(
input,
has_new_styles: parse_bool_bits >>
change_line_style: call!(parse_bool_bits) >>
change_right_fill: call!(parse_bool_bits) >>
change_left_fill: call!(parse_bool_bits) >>
has_move_to: call!(parse_bool_bits) >>
move_to: cond!(has_move_to,
do_parse!(
move_to_bits: apply!(parse_u16_bits, 5) >>
x: apply!(parse_i32_bits, move_to_bits as usize) >>
y: apply!(parse_i32_bits, move_to_bits as usize) >>
(ast::Vector2D {x: x, y: y})
)
) >>
left_fill: cond!(change_left_fill, apply!(parse_u16_bits, fill_bits)) >>
right_fill: cond!(change_right_fill, apply!(parse_u16_bits, fill_bits)) >>
line_style: cond!(change_line_style, apply!(parse_u16_bits, line_bits)) >>
styles: map!(
cond!(has_new_styles, apply!(parse_shape_styles_bits, version)),
|styles| match styles {
Option::Some(styles) => (Option::Some(styles.fill), Option::Some(styles.line), styles.fill_bits, styles.line_bits),
Option::None => (Option::None, Option::None, fill_bits, line_bits),
}
) >>
((
ast::shape_records::StyleChange {
move_to: move_to,
left_fill: left_fill.map(|x| x as usize),
right_fill: right_fill.map(|x| x as usize),
line_style: line_style.map(|x| x as usize),
fill_styles: styles.0,
line_styles: styles.1,
},
(styles.2, styles.3),
))
)
}
pub fn parse_list_length(input: &[u8], support_extended: bool) -> IResult<&[u8], usize> {
match parse_u8(input) {
IResult::Done(remaining_input, u8_len) => {
if u8_len == 0xff && support_extended {
parse_le_u16(remaining_input).map(|x| x as usize)
} else {
IResult::Done(remaining_input, u8_len as usize)
}
}
IResult::Error(e) => IResult::Error(e),
IResult::Incomplete(n) => IResult::Incomplete(n),
}
}
pub fn parse_fill_style_list(input: &[u8], version: ShapeVersion) -> IResult<&[u8], Vec<ast::FillStyle>> {
length_count!(input, apply!(parse_list_length, version != ShapeVersion::Shape1), apply!(parse_fill_style, version == ShapeVersion::Shape3))
}
#[allow(unused_variables)]
pub fn parse_fill_style(input: &[u8], with_alpha: bool) -> IResult<&[u8], ast::FillStyle> {
switch!(input, parse_u8,
0x00 => map!(apply!(parse_solid_fill, with_alpha), |fill| ast::FillStyle::Solid(fill)) |
0x10 => map!(apply!(parse_linear_gradient_fill, with_alpha), |fill| ast::FillStyle::LinearGradient(fill)) |
0x12 => map!(apply!(parse_radial_gradient_fill, with_alpha), |fill| ast::FillStyle::RadialGradient(fill)) |
0x13 => map!(apply!(parse_focal_gradient_fill, with_alpha), |fill| ast::FillStyle::FocalGradient(fill)) |
0x40 => map!(apply!(parse_bitmap_fill, true, true), |fill| ast::FillStyle::Bitmap(fill)) |
0x41 => map!(apply!(parse_bitmap_fill, false, true), |fill| ast::FillStyle::Bitmap(fill)) |
0x42 => map!(apply!(parse_bitmap_fill, true, false), |fill| ast::FillStyle::Bitmap(fill)) |
0x43 => map!(apply!(parse_bitmap_fill, false, false), |fill| ast::FillStyle::Bitmap(fill))
// TODO: Error
)
}
pub fn parse_bitmap_fill(input: &[u8], repeating: bool, smoothed: bool) -> IResult<&[u8], ast::fill_styles::Bitmap> {
do_parse!(
input,
bitmap_id: parse_le_u16 >>
matrix: parse_matrix >>
(ast::fill_styles::Bitmap {
bitmap_id: bitmap_id,
matrix: matrix,
repeating: repeating,
smoothed: smoothed
})
)
}
pub fn parse_focal_gradient_fill(input: &[u8], with_alpha: bool) -> IResult<&[u8], ast::fill_styles::FocalGradient> {
do_parse!(
input,
matrix: parse_matrix >>
gradient: apply!(parse_gradient, with_alpha) >>
focal_point: parse_le_fixed8_p8 >>
(ast::fill_styles::FocalGradient {
matrix: matrix,
gradient: gradient,
focal_point: focal_point
})
)
}
pub fn parse_linear_gradient_fill(input: &[u8], with_alpha: bool) -> IResult<&[u8], ast::fill_styles::LinearGradient> {
do_parse!(
input,
matrix: parse_matrix >>
gradient: apply!(parse_gradient, with_alpha) >>
(ast::fill_styles::LinearGradient {
matrix: matrix,
gradient: gradient
})
)
}
pub fn parse_radial_gradient_fill(input: &[u8], with_alpha: bool) -> IResult<&[u8], ast::fill_styles::RadialGradient> {
do_parse!(
input,
matrix: parse_matrix >>
gradient: apply!(parse_gradient, with_alpha) >>
(ast::fill_styles::RadialGradient {
matrix: matrix,
gradient: gradient
})
)
}
#[allow(unused_variables)]
pub fn parse_solid_fill(input: &[u8], with_alpha: bool) -> IResult<&[u8], ast::fill_styles::Solid> {
do_parse!(
input,
color: switch!(value!(with_alpha),
true => call!(parse_straight_s_rgba8) |
false => map!(parse_s_rgb8, |c| ast::StraightSRgba8 {r: c.r, g: c.g, b: c.b, a: 255})
) >>
(ast::fill_styles::Solid {color: color})
)
}
pub fn parse_line_style_list(input: &[u8], version: ShapeVersion) -> IResult<&[u8], Vec<ast::LineStyle>> {
length_count!(input, apply!(parse_list_length, version != ShapeVersion::Shape1), parse_line_style)
}
pub fn parse_line_style(input: &[u8]) -> IResult<&[u8], ast::LineStyle> {
do_parse!(
input,
width: parse_le_u16 >>
color: parse_s_rgb8 >>
(
ast::LineStyle {
width: width,
start_cap: ast::CapStyle::Round,
end_cap: ast::CapStyle::Round,
join: ast::JoinStyle::Round,
no_h_scale: false,
no_v_scale: false,
no_close: false,
pixel_hinting: false,
fill: ast::FillStyle::Solid(
ast::fill_styles::Solid {
color: ast::StraightSRgba8 {
r: color.r,
g: color.g,
b: color.b,
a: 255
}
}
),
})
)
}
|
mod test_block_chain;
mod test_opened_block;
|
//! General Purpose Input / Output
//!
//! This module makes heavy use of types to try and ensure you can't have a
//! pin in a mode you didn't expect.
//!
//! Most pins start in the `Tristate` state. You can call methods to convert
//! them to inputs, outputs or put them into Alternate Function mode (e.g. to
//! use with a UART).
//!
//! Some of the modes require extra information, and for that we use the so-
//! called 'Turbo Fish` syntax, which looks like `method::<TYPE>`.
//!
//! If the operation is non-atomic, then you need to pass a mut-reference to
//! the port's control structure. This ensures you can't change two pins in
//! two threads at the same time. If the operation is fully atomic (using the
//! chip's bit-banding feature) then this argument is not required.
//!
//! Here's an example:
//!
//! ```
//! # use tm4c123x_hal::*;
//! # use tm4c123x_hal::sysctl::SysctlExt;
//! # use tm4c123x_hal::gpio::GpioExt;
//! # fn foo() {
//! let p = Peripherals::take().unwrap();
//! let mut sc = p.SYSCTL.constrain();
//! let mut portb = p.GPIO_PORTB.split(&sc.power_control);
//! let timer_output_pin = portb.pb0.into_af_push_pull::<gpio::AF7>(&mut portb.control);
//! let uart_tx_pin = portb.pb1.into_af_open_drain::<gpio::AF1, gpio::PullUp>(&mut portb.control);
//! let blue_led = portb.pb2.into_push_pull_output();
//! let button = portb.pb3.into_pull_up_input();
//! # }
//! ```
use bb;
use core::marker::PhantomData;
use hal::digital::{InputPin, OutputPin, StatefulOutputPin};
use sysctl;
/// Extension trait to split a GPIO peripheral in independent pins and registers
pub trait GpioExt {
/// The to split the GPIO into
type Parts;
/// Splits the GPIO block into independent pins and registers
fn split(self, power_control: &sysctl::PowerControl) -> Self::Parts;
}
/// All unlocked pin modes implement this
pub trait IsUnlocked {}
/// All input modes implement this
pub trait InputMode {}
/// All output modes implement this
pub trait OutputMode {}
/// OpenDrain modes implement this
pub trait OpenDrainMode {
/// Is pull-up enabled
fn pup() -> bool;
}
/// All the different Alternate Functions you can choose implement this
pub trait AlternateFunctionChoice {
/// Which Alternate Function (numbered 1 through 15) is this?
fn number() -> u32;
}
/// Input mode (type state)
pub struct Input<MODE>
where
MODE: InputMode,
{
_mode: PhantomData<MODE>,
}
impl<MODE> IsUnlocked for Input<MODE>
where
MODE: InputMode,
{
}
/// Sub-mode of Input: Floating input (type state)
pub struct Floating;
impl InputMode for Floating {}
impl OpenDrainMode for Floating {
/// Pull-up is not enabled
fn pup() -> bool {
false
}
}
/// Sub-mode of Input: Pulled down input (type state)
pub struct PullDown;
impl InputMode for PullDown {}
/// Sub-mode of Input: Pulled up input (type state)
pub struct PullUp;
impl InputMode for PullUp {}
impl OpenDrainMode for PullUp {
/// Pull-up is enabled
fn pup() -> bool {
true
}
}
/// Tri-state
pub struct Tristate;
impl IsUnlocked for Tristate {}
/// Output mode (type state)
pub struct Output<MODE>
where
MODE: OutputMode,
{
_mode: PhantomData<MODE>,
}
impl<MODE> IsUnlocked for Output<MODE>
where
MODE: OutputMode,
{
}
/// AlternateFunction mode (type state for a GPIO pin)
pub struct AlternateFunction<AF, MODE>
where
AF: AlternateFunctionChoice,
MODE: OutputMode,
{
_func: PhantomData<AF>,
_mode: PhantomData<MODE>,
}
impl<AF, MODE> IsUnlocked for AlternateFunction<AF, MODE>
where
AF: AlternateFunctionChoice,
MODE: OutputMode,
{
}
/// Sub-mode of Output/AlternateFunction: Push pull output (type state for Output)
pub struct PushPull;
impl OutputMode for PushPull {}
/// Sub-mode of Output/AlternateFunction: Open drain output (type state for Output)
pub struct OpenDrain<ODM>
where
ODM: OpenDrainMode,
{
_pull: PhantomData<ODM>,
}
impl<ODM> OutputMode for OpenDrain<ODM>
where
ODM: OpenDrainMode,
{
}
/// Alternate function 1 (type state)
pub struct AF1;
impl AlternateFunctionChoice for AF1 {
fn number() -> u32 {
return 1;
}
}
/// Alternate function 2 (type state)
pub struct AF2;
impl AlternateFunctionChoice for AF2 {
fn number() -> u32 {
return 2;
}
}
/// Alternate function 3 (type state)
pub struct AF3;
impl AlternateFunctionChoice for AF3 {
fn number() -> u32 {
return 3;
}
}
/// Alternate function 4 (type state)
pub struct AF4;
impl AlternateFunctionChoice for AF4 {
fn number() -> u32 {
return 4;
}
}
/// Alternate function 5 (type state)
pub struct AF5;
impl AlternateFunctionChoice for AF5 {
fn number() -> u32 {
return 5;
}
}
/// Alternate function 6 (type state)
pub struct AF6;
impl AlternateFunctionChoice for AF6 {
fn number() -> u32 {
return 6;
}
}
/// Alternate function 7 (type state)
pub struct AF7;
impl AlternateFunctionChoice for AF7 {
fn number() -> u32 {
return 7;
}
}
/// Alternate function 8 (type state)
pub struct AF8;
impl AlternateFunctionChoice for AF8 {
fn number() -> u32 {
return 8;
}
}
/// Alternate function 9 (type state)
pub struct AF9;
impl AlternateFunctionChoice for AF9 {
fn number() -> u32 {
return 9;
}
}
// 10 through 13 are not available on this chip.
/// Alternate function 14 (type state)
pub struct AF14;
impl AlternateFunctionChoice for AF14 {
fn number() -> u32 {
return 14;
}
}
/// Pin is locked through the GPIOCR register
pub struct Locked;
/// Sets when a GPIO pin triggers an interrupt.
pub enum InterruptMode {
/// Interrupt when level is low
LevelLow,
/// Interrupt when level is high
LevelHigh,
/// Interrupt on rising edge
EdgeRising,
/// Interrupt on falling edge
EdgeFalling,
/// Interrupt on both rising and falling edges
EdgeBoth,
/// Disable interrupts on this pin
Disabled,
}
macro_rules! gpio {
($GPIOX:ident, $gpiox:ident, $iopd:ident, $PXx:ident, [
$($PXi:ident: ($pxi:ident, $i:expr, $MODE:ty),)+
]) => {
/// GPIO
pub mod $gpiox {
use super::*;
use tm4c123x::$GPIOX;
/// Provides mutual-exclusion for certain GPIO operations (such as
/// selecting an alternate mode) that can't be done atomically.
pub struct GpioControl {
_0: (),
}
/// GPIO parts
pub struct Parts {
/// Pass an &mut reference to methods that require it.
pub control: GpioControl,
$(
/// Pin
pub $pxi: $PXi<$MODE>,
)+
}
impl GpioExt for $GPIOX {
type Parts = Parts;
/// Break this GPIO port into separate pins
fn split(self, pc: &sysctl::PowerControl) -> Parts {
sysctl::control_power(
pc, sysctl::Domain::$iopd,
sysctl::RunMode::Run, sysctl::PowerState::On);
sysctl::reset(pc, sysctl::Domain::$iopd);
Parts {
control: GpioControl { _0: () },
$(
$pxi: $PXi { _mode: PhantomData },
)+
}
}
}
/// Partially erased pin
pub struct $PXx<MODE> {
i: u8,
_mode: PhantomData<MODE>,
}
impl<MODE> StatefulOutputPin for $PXx<Output<MODE>> where MODE: OutputMode {
fn is_set_high(&self) -> bool {
let p = unsafe { &*$GPIOX::ptr() };
bb::read_bit(&p.data, self.i)
}
fn is_set_low(&self) -> bool {
!self.is_set_high()
}
}
impl<MODE> OutputPin for $PXx<Output<MODE>> where MODE: OutputMode {
fn set_high(&mut self) {
let p = unsafe { &*$GPIOX::ptr() };
unsafe { bb::change_bit(&p.data, self.i, true); }
}
fn set_low(&mut self) {
let p = unsafe { &*$GPIOX::ptr() };
unsafe { bb::change_bit(&p.data, self.i, false); }
}
}
impl<MODE> InputPin for $PXx<Input<MODE>> where MODE: InputMode {
fn is_high(&self) -> bool {
let p = unsafe { &*$GPIOX::ptr() };
bb::read_bit(&p.data, self.i)
}
fn is_low(&self) -> bool {
!self.is_high()
}
}
impl<MODE> $PXx<Input<MODE>> where MODE: InputMode {
/// Enables or disables interrupts on this GPIO pin.
pub fn set_interrupt_mode(&mut self, mode: InterruptMode) {
let p = unsafe { &*$GPIOX::ptr() };
unsafe { bb::change_bit(&p.im, self.i, false); }
match mode {
InterruptMode::LevelHigh => {
// IM &= ~self.i;
unsafe { bb::change_bit(&p.im, self.i, false); }
// IS |= self.i;
unsafe { bb::change_bit(&p.is, self.i, true); }
// IBE &= ~self.i;
unsafe { bb::change_bit(&p.ibe, self.i, false); }
// IEV |= self.i;
unsafe { bb::change_bit(&p.iev, self.i, true); }
// IM |= self.i;
unsafe { bb::change_bit(&p.im, self.i, true); }
},
InterruptMode::LevelLow => {
// IM &= ~self.i;
unsafe { bb::change_bit(&p.im, self.i, false); }
// IS |= self.i;
unsafe { bb::change_bit(&p.is, self.i, true); }
// IBE &= ~self.i;
unsafe { bb::change_bit(&p.ibe, self.i, false); }
// IEV &= ~self.i;
unsafe { bb::change_bit(&p.iev, self.i, false); }
// IM |= self.i;
unsafe { bb::change_bit(&p.im, self.i, true); }
},
InterruptMode::EdgeRising => {
// IM &= ~self.i;
unsafe { bb::change_bit(&p.im, self.i, false); }
// IS &= ~self.i;
unsafe { bb::change_bit(&p.is, self.i, false); }
// IBE &= ~self.i;
unsafe { bb::change_bit(&p.ibe, self.i, false); }
// IEV |= self.i;
unsafe { bb::change_bit(&p.iev, self.i, true); }
// IM |= self.i;
unsafe { bb::change_bit(&p.im, self.i, true); }
},
InterruptMode::EdgeFalling => {
// IM &= ~self.i;
unsafe { bb::change_bit(&p.im, self.i, false); }
// IS &= ~self.i;
unsafe { bb::change_bit(&p.is, self.i, false); }
// IBE &= ~self.i;
unsafe { bb::change_bit(&p.ibe, self.i, false); }
// IEV &= ~self.i;
unsafe { bb::change_bit(&p.iev, self.i, false); }
// IM |= self.i;
unsafe { bb::change_bit(&p.im, self.i, true); }
},
InterruptMode::EdgeBoth => {
// IM &= ~self.i;
unsafe { bb::change_bit(&p.im, self.i, false); }
// IS &= ~self.i;
unsafe { bb::change_bit(&p.is, self.i, false); }
// IBE |= self.i;
unsafe { bb::change_bit(&p.ibe, self.i, true); }
// IEV |= self.i;
unsafe { bb::change_bit(&p.iev, self.i, true); }
// IM |= self.i;
unsafe { bb::change_bit(&p.im, self.i, true); }
},
InterruptMode::Disabled => {
// IM &= ~self.i;
unsafe { bb::change_bit(&p.im, self.i, false); }
},
}
}
/// Marks the interrupt for this pin as handled. You should
/// call this (or perform its functionality) from the ISR.
pub fn clear_interrupt(&self) {
let p = unsafe { &*$GPIOX::ptr() };
unsafe { bb::change_bit(&p.icr, self.i, true); }
}
}
$(
/// Pin
pub struct $PXi<MODE> {
_mode: PhantomData<MODE>,
}
impl<MODE> $PXi<MODE> where MODE: IsUnlocked {
/// Configures the pin to serve as alternate function 1 through 15.
/// Disables open-drain to make the output a push-pull.
pub fn into_af_push_pull<AF>(
self,
_gpio_control: &mut GpioControl,
) -> $PXi<AlternateFunction<AF, PushPull>> where AF: AlternateFunctionChoice {
let p = unsafe { &*$GPIOX::ptr() };
let mask = 0xF << ($i * 4);
let bits = AF::number() << ($i * 4);
unsafe {
p.pctl.modify(|r, w| w.bits((r.bits() & !mask) | bits));
}
unsafe { bb::change_bit(&p.afsel, $i, true); }
unsafe { bb::change_bit(&p.dir, $i, false); }
unsafe { bb::change_bit(&p.odr, $i, false); }
unsafe { bb::change_bit(&p.pur, $i, false); }
unsafe { bb::change_bit(&p.pdr, $i, false); }
unsafe { bb::change_bit(&p.den, $i, true); }
$PXi { _mode: PhantomData }
}
/// Configures the pin to serve as alternate function 1 through 15.
/// Enables open-drain (useful for I2C SDA, for example).
pub fn into_af_open_drain<AF, ODM>(
self,
_gpio_control: &mut GpioControl,
) -> $PXi<AlternateFunction<AF, OpenDrain<ODM>>> where AF: AlternateFunctionChoice, ODM: OpenDrainMode {
let p = unsafe { &*$GPIOX::ptr() };
let mask = 0xF << ($i * 4);
let bits = AF::number() << ($i * 4);
unsafe {
p.pctl.modify(|r, w| w.bits((r.bits() & !mask) | bits));
}
unsafe { bb::change_bit(&p.afsel, $i, true); }
unsafe { bb::change_bit(&p.dir, $i, false); }
unsafe { bb::change_bit(&p.odr, $i, true); }
unsafe { bb::change_bit(&p.pur, $i, ODM::pup()); }
unsafe { bb::change_bit(&p.pdr, $i, false); }
unsafe { bb::change_bit(&p.den, $i, true); }
$PXi { _mode: PhantomData }
}
/// Configures the pin to operate as a floating input pin
pub fn into_floating_input(
self
) -> $PXi<Input<Floating>> {
let p = unsafe { &*$GPIOX::ptr() };
unsafe { bb::change_bit(&p.afsel, $i, false); }
unsafe { bb::change_bit(&p.dir, $i, false); }
unsafe { bb::change_bit(&p.odr, $i, false); }
unsafe { bb::change_bit(&p.pur, $i, false); }
unsafe { bb::change_bit(&p.pdr, $i, false); }
unsafe { bb::change_bit(&p.den, $i, true); }
$PXi { _mode: PhantomData }
}
/// Configures the pin to operate as a pulled down input pin
pub fn into_pull_down_input(
self
) -> $PXi<Input<PullDown>> {
let p = unsafe { &*$GPIOX::ptr() };
unsafe { bb::change_bit(&p.afsel, $i, false); }
unsafe { bb::change_bit(&p.dir, $i, false); }
unsafe { bb::change_bit(&p.odr, $i, false); }
unsafe { bb::change_bit(&p.pur, $i, false); }
unsafe { bb::change_bit(&p.pdr, $i, true); }
unsafe { bb::change_bit(&p.den, $i, true); }
$PXi { _mode: PhantomData }
}
/// Configures the pin to operate as a pulled up input pin
pub fn into_pull_up_input(
self
) -> $PXi<Input<PullUp>> {
let p = unsafe { &*$GPIOX::ptr() };
unsafe { bb::change_bit(&p.afsel, $i, false); }
unsafe { bb::change_bit(&p.dir, $i, false); }
unsafe { bb::change_bit(&p.odr, $i, false); }
unsafe { bb::change_bit(&p.pur, $i, true); }
unsafe { bb::change_bit(&p.pdr, $i, false); }
unsafe { bb::change_bit(&p.den, $i, true); }
$PXi { _mode: PhantomData }
}
/// Configures the pin to operate as an open drain output pin
pub fn into_open_drain_output<ODM>(
self
) -> $PXi<Output<OpenDrain<ODM>>> where ODM: OpenDrainMode {
let p = unsafe { &*$GPIOX::ptr() };
unsafe { bb::change_bit(&p.afsel, $i, false); }
unsafe { bb::change_bit(&p.dir, $i, true); }
unsafe { bb::change_bit(&p.odr, $i, true); }
unsafe { bb::change_bit(&p.pur, $i, ODM::pup()); }
unsafe { bb::change_bit(&p.pdr, $i, false); }
unsafe { bb::change_bit(&p.den, $i, true); }
$PXi { _mode: PhantomData }
}
/// Configures the pin to operate as an push pull output pin
pub fn into_push_pull_output(
self
) -> $PXi<Output<PushPull>> {
let p = unsafe { &*$GPIOX::ptr() };
unsafe { bb::change_bit(&p.afsel, $i, false); }
unsafe { bb::change_bit(&p.dir, $i, true); }
unsafe { bb::change_bit(&p.odr, $i, false); }
unsafe { bb::change_bit(&p.pur, $i, false); }
unsafe { bb::change_bit(&p.pdr, $i, false); }
unsafe { bb::change_bit(&p.den, $i, true); }
$PXi { _mode: PhantomData }
}
/// Configures the pin as tri-state
pub fn into_tri_state(
self
) -> $PXi<Tristate> {
let p = unsafe { &*$GPIOX::ptr() };
unsafe { bb::change_bit(&p.den, $i, false); }
unsafe { bb::change_bit(&p.afsel, $i, false); }
unsafe { bb::change_bit(&p.dir, $i, false); }
unsafe { bb::change_bit(&p.odr, $i, false); }
unsafe { bb::change_bit(&p.pur, $i, false); }
unsafe { bb::change_bit(&p.pdr, $i, false); }
$PXi { _mode: PhantomData }
}
}
impl<MODE> $PXi<MODE> {
/// Erases the pin number from the type
///
/// This is useful when you want to collect the pins into an array where you
/// need all the elements to have the same type
pub fn downgrade(self) -> $PXx<MODE> {
$PXx {
i: $i,
_mode: self._mode,
}
}
}
impl<MODE> StatefulOutputPin for $PXi<Output<MODE>> where MODE: OutputMode {
fn is_set_high(&self) -> bool {
let p = unsafe { &*$GPIOX::ptr() };
bb::read_bit(&p.data, $i)
}
fn is_set_low(&self) -> bool {
!self.is_set_high()
}
}
impl<MODE> OutputPin for $PXi<Output<MODE>> where MODE: OutputMode {
fn set_high(&mut self) {
let p = unsafe { &*$GPIOX::ptr() };
unsafe { bb::change_bit(&p.data, $i, true); }
}
fn set_low(&mut self) {
let p = unsafe { &*$GPIOX::ptr() };
unsafe { bb::change_bit(&p.data, $i, false); }
}
}
impl<MODE> InputPin for $PXi<Input<MODE>> where MODE: InputMode {
fn is_high(&self) -> bool {
let p = unsafe { &*$GPIOX::ptr() };
bb::read_bit(&p.data, $i)
}
fn is_low(&self) -> bool {
!self.is_high()
}
}
impl<MODE> $PXi<Input<MODE>> where MODE: InputMode {
/// Enables or disables interrupts on this GPIO pin.
pub fn set_interrupt_mode(&mut self, mode: InterruptMode) {
let p = unsafe { &*$GPIOX::ptr() };
unsafe { bb::change_bit(&p.im, $i, false); }
match mode {
InterruptMode::LevelHigh => {
// IM &= ~$i;
unsafe { bb::change_bit(&p.im, $i, false); }
// IS |= $i;
unsafe { bb::change_bit(&p.is, $i, true); }
// IBE &= ~$i;
unsafe { bb::change_bit(&p.ibe, $i, false); }
// IEV |= $i;
unsafe { bb::change_bit(&p.iev, $i, true); }
// IM |= $i;
unsafe { bb::change_bit(&p.im, $i, true); }
},
InterruptMode::LevelLow => {
// IM &= ~$i;
unsafe { bb::change_bit(&p.im, $i, false); }
// IS |= $i;
unsafe { bb::change_bit(&p.is, $i, true); }
// IBE &= ~$i;
unsafe { bb::change_bit(&p.ibe, $i, false); }
// IEV &= ~$i;
unsafe { bb::change_bit(&p.iev, $i, false); }
// IM |= $i;
unsafe { bb::change_bit(&p.im, $i, true); }
},
InterruptMode::EdgeRising => {
// IM &= ~$i;
unsafe { bb::change_bit(&p.im, $i, false); }
// IS &= ~$i;
unsafe { bb::change_bit(&p.is, $i, false); }
// IBE &= ~$i;
unsafe { bb::change_bit(&p.ibe, $i, false); }
// IEV |= $i;
unsafe { bb::change_bit(&p.iev, $i, true); }
// IM |= $i;
unsafe { bb::change_bit(&p.im, $i, true); }
},
InterruptMode::EdgeFalling => {
// IM &= ~$i;
unsafe { bb::change_bit(&p.im, $i, false); }
// IS &= ~$i;
unsafe { bb::change_bit(&p.is, $i, false); }
// IBE &= ~$i;
unsafe { bb::change_bit(&p.ibe, $i, false); }
// IEV &= ~$i;
unsafe { bb::change_bit(&p.iev, $i, false); }
// IM |= $i;
unsafe { bb::change_bit(&p.im, $i, true); }
},
InterruptMode::EdgeBoth => {
// IM &= ~$i;
unsafe { bb::change_bit(&p.im, $i, false); }
// IS &= ~$i;
unsafe { bb::change_bit(&p.is, $i, false); }
// IBE |= $i;
unsafe { bb::change_bit(&p.ibe, $i, true); }
// IEV |= $i;
unsafe { bb::change_bit(&p.iev, $i, true); }
// IM |= $i;
unsafe { bb::change_bit(&p.im, $i, true); }
},
InterruptMode::Disabled => {
// IM &= ~$i;
unsafe { bb::change_bit(&p.im, $i, false); }
},
}
}
/// Marks the interrupt for this pin as handled. You should
/// call this (or perform its functionality) from the ISR.
pub fn clear_interrupt(&self) {
let p = unsafe { &*$GPIOX::ptr() };
unsafe { bb::change_bit(&p.icr, $i, true); }
}
}
impl $PXi<Locked> {
/// Unlock a GPIO so that it can be used. This is required
/// on 'special' GPIOs that the manufacturer doesn't want
/// you to change by accident - like NMI and JTAG pins.
pub fn unlock(self, _gpio_control: &mut GpioControl) -> $PXi<Tristate> {
let p = unsafe { &*$GPIOX::ptr() };
p.lock.write(|w| w.lock().key());
p.cr.modify(|_, w| unsafe { w.bits(1 << $i) });
p.lock.write(|w| w.lock().unlocked());
unsafe { bb::change_bit(&p.den, $i, false); }
unsafe { bb::change_bit(&p.afsel, $i, false); }
unsafe { bb::change_bit(&p.dir, $i, false); }
unsafe { bb::change_bit(&p.odr, $i, false); }
unsafe { bb::change_bit(&p.pur, $i, false); }
unsafe { bb::change_bit(&p.pdr, $i, false); }
$PXi { _mode: PhantomData }
}
}
)+
}
}
}
gpio!(GPIO_PORTA, gpioa, GpioA, PAx, [
PA0: (pa0, 0, Tristate),
PA1: (pa1, 1, Tristate),
PA2: (pa2, 2, Tristate),
PA3: (pa3, 3, Tristate),
PA4: (pa4, 4, Tristate),
PA5: (pa5, 5, Tristate),
PA6: (pa6, 6, Tristate),
PA7: (pa7, 7, Tristate),
]);
gpio!(GPIO_PORTB, gpiob, GpioB, PBx, [
PB0: (pb0, 0, Tristate),
PB1: (pb1, 1, Tristate),
PB2: (pb2, 2, Tristate),
PB3: (pb3, 3, Tristate),
PB4: (pb4, 4, Tristate),
PB5: (pb5, 5, Tristate),
PB6: (pb6, 6, Tristate),
PB7: (pb7, 7, Tristate),
]);
gpio!(GPIO_PORTC, gpioc, GpioC, PCx, [
PC0: (pc0, 0, Locked), // JTAG/SWD pin
PC1: (pc1, 1, Locked), // JTAG/SWD pin
PC2: (pc2, 2, Locked), // JTAG/SWD pin
PC3: (pc3, 3, Locked), // JTAG/SWD pin
PC4: (pc4, 4, Tristate),
PC5: (pc5, 5, Tristate),
PC6: (pc6, 6, Tristate),
PC7: (pc7, 7, Tristate),
]);
gpio!(GPIO_PORTD, gpiod, GpioD, PDx, [
PD0: (pd0, 0, Tristate),
PD1: (pd1, 1, Tristate),
PD2: (pd2, 2, Tristate),
PD3: (pd3, 3, Tristate),
PD4: (pd4, 4, Tristate),
PD5: (pd5, 5, Tristate),
PD6: (pd6, 6, Tristate),
PD7: (pd7, 7, Locked), // NMI pin
]);
gpio!(GPIO_PORTE, gpioe, GpioE, PEx, [
PE0: (pe0, 0, Tristate),
PE1: (pe1, 1, Tristate),
PE2: (pe2, 2, Tristate),
PE3: (pe3, 3, Tristate),
PE4: (pe4, 4, Tristate),
PE5: (pe5, 5, Tristate),
PE6: (pe6, 6, Tristate),
PE7: (pe7, 7, Tristate),
]);
gpio!(GPIO_PORTF, gpiof, GpioF, PFx, [
PF0: (pf0, 0, Locked), // NMI pin
PF1: (pf1, 1, Tristate),
PF2: (pf2, 2, Tristate),
PF3: (pf3, 3, Tristate),
PF4: (pf4, 4, Tristate),
PF5: (pf5, 5, Tristate),
PF6: (pf6, 6, Tristate),
PF7: (pf7, 7, Tristate),
]);
|
use serde::de::DeserializeOwned;
use crate::error::Result;
use crate::service::CONTEXT;
use crate::service::cache_service::CacheProxyType::Mem;
use std::time::Duration;
use async_trait::async_trait;
use serde::{Serialize};
pub enum CacheProxyType {
Mem,
Redis,
}
#[async_trait]
pub trait ICacheService {
async fn set_string(&self, k: &str, v: &str) -> Result<String>;
async fn get_string(&self, k: &str) -> Result<String>;
async fn set_json<T>(&self, k: &str, v: &T) -> Result<String> where T: Serialize+Sync;
async fn get_json<T>(&self, k: &str) -> Result<T> where T: DeserializeOwned+Sync;
async fn set_string_ex(&self, k: &str, v: &str, ex: Option<Duration>) -> Result<String>;
async fn ttl(&self, k: &str) -> Result<i64>;
}
///缓存服务-可选缓存介质,mem,redis
pub struct CacheService {
pub inner: CacheProxyType,
}
impl Default for CacheService {
fn default() -> Self {
Self {
inner: Mem,
}
}
}
#[async_trait]
impl ICacheService for CacheService {
async fn set_string(&self, k: &str, v: &str) -> Result<String> {
return match self.inner {
Mem => {
CONTEXT.mem_service.set_string(k, v).await
}
CacheProxyType::Redis => {
CONTEXT.redis_service.set_string(k, v).await
}
};
}
async fn get_string(&self, k: &str) -> Result<String> {
return match self.inner {
Mem => {
CONTEXT.mem_service.get_string(k).await
}
CacheProxyType::Redis => {
CONTEXT.redis_service.get_string(k).await
}
};
}
async fn set_json<T>(&self, k: &str, v: &T) -> Result<String>
where
T: Serialize+Sync,
{
return match self.inner {
Mem => {
CONTEXT.mem_service.set_json::<T>(k, v).await
}
CacheProxyType::Redis => {
CONTEXT.redis_service.set_json::<T>(k, v).await
}
};
}
async fn get_json<T>(&self, k: &str) -> Result<T>
where
T: DeserializeOwned+Sync,
{
return match self.inner {
Mem => {
CONTEXT.mem_service.get_json(k).await
}
CacheProxyType::Redis => {
CONTEXT.redis_service.get_json(k).await
}
};
}
async fn set_string_ex(&self, k: &str, v: &str, ex: Option<Duration>) -> Result<String> {
return match self.inner {
Mem => {
CONTEXT.mem_service.set_string_ex(k, v, ex).await
}
CacheProxyType::Redis => {
CONTEXT.redis_service.set_string_ex(k, v, ex).await
}
};
}
async fn ttl(&self, k: &str) -> Result<i64> {
return match self.inner {
Mem => {
CONTEXT.mem_service.ttl(k).await
}
CacheProxyType::Redis => {
CONTEXT.redis_service.ttl(k).await
}
};
}
}
|
/*
chapter 4
syntax and semantics
*/
#[derive(Debug)]
struct Foo;
fn main() {
println!("{:?}", Foo);
}
// deriving is limited to a certain set of traits:
/*
Clone
Copy
Debug
Default
Eq
Hash
Ord
PartialEq
PartialOrd
*/
// output should be:
/*
*/
|
// Rust's std::result type
enum Result<T, E> {
Ok(T),
Err(E),
}
// Rust's std::option type
enum Option<T> {
Some(T),
None,
}
fn divide(a: i32, b: i32) -> Result<i32, &'static str> {
match b {
0 => Result::Err("divide by zero"),
_ => Result::Ok(a / b),
}
}
fn find_item(nr: i32) -> Option<&'static str> {
match nr {
0 => Option::Some("Rust"),
_ => Option::None,
}
}
fn main() {
match divide(1, 1) {
Result::Ok(result) => println!("1 / 1 = {}", result),
Result::Err(reason) => println!("Error: {}", reason),
}
match divide(1, 0) {
Result::Ok(result) => println!("1 / 0 = {}", result),
Result::Err(reason) => println!("Error: {}", reason),
}
match find_item(0) {
Option::Some(result) => println!("Item: {}", result),
Option::None => println!("No item was found"),
}
match find_item(1) {
Option::Some(result) => println!("Item: {}", result),
Option::None => println!("No item was found"),
}
}
|
#![feature(plugin)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate wuligege;
extern crate json;
use wuligege::user::User;
use rocket::response::content;
#[get("/")]
fn index() -> content::JSON<String> {
let user = User::new("simon".to_string(),"123666".to_string());
content::JSON(user.to_json())
}
#[get("/")]
fn hello() -> String {
let mut x = 5;
let y = &mut x;
*y += 1;
// "hello".to_string()
// y.to_string()
let goodbye = wuligege::japanese::farewells::goodbye();
let greetings = wuligege::japanese::greetings::hello();
let helloworld = goodbye +"这是牛逼的"+ &greetings;
helloworld
}
#[get("/world")] // <- route attribute
fn world() -> &'static str { // <- request handler
"Hello, world!"
}
fn main() {
rocket::ignite()
.mount("/", routes![index])
.mount("/hello", routes![hello])
.mount("/hello", routes![world])
.launch();
}
|
use super::node::FileNode;
use super::node::NODE_TYPE_DIR;
use std::iter::repeat;
static SPACE_ONE: &'static str = " ";
static SPACE_THREE: &'static str = " ";
static SPACE_FOUR: &'static str = " ";
static HORIZONTAL_LINE: &'static str = "─";
static VERTICAL_LINE: &'static str = "│";
static T_PREFIX: &'static str = "├";
static END_PREFIX: &'static str = "└";
pub fn print_file_node_tree(
node: &FileNode,
prefix: &mut Vec<&str>,
depth: u64,
level: u64,
human: bool,
) {
let n_children = node.children.borrow().len();
for (i, x) in node.children.borrow().iter().enumerate() {
// first
if i == 0 {
prefix.push(T_PREFIX);
}
// last
if i + 1 == n_children {
prefix.pop();
prefix.push(END_PREFIX);
}
println!(
"{}{} {} {}",
prefix.join(""),
repeat(HORIZONTAL_LINE).take(2).collect::<String>(),
x.name,
get_size_text(x.total_size.get(), human)
);
if x.node_type == NODE_TYPE_DIR && depth < level {
if x.name.chars().next().unwrap() == '.' {
continue;
}
prefix.pop();
// last
if i + 1 == n_children {
prefix.push(SPACE_ONE);
} else {
prefix.push(VERTICAL_LINE);
}
prefix.push(SPACE_THREE);
print_file_node_tree(x, &mut prefix.to_vec(), depth + 1, level, human);
prefix.pop();
prefix.pop();
prefix.push(T_PREFIX);
}
}
}
fn print_node(node: &FileNode, human: bool, depth: u64) {
println!(
"{}{} {}",
repeat(SPACE_FOUR)
.take((depth - 1) as usize)
.collect::<String>(),
node.name,
get_size_text(node.total_size.get(), human)
);
}
pub fn print_file_node_simplely(node: &FileNode, depth: u64, level: u64, human: bool) {
for x in node.children.borrow().iter() {
print_node(x, human, depth);
if x.node_type == NODE_TYPE_DIR && depth < level {
if x.name.chars().next().unwrap() == '.' {
continue;
}
print_file_node_simplely(x, depth + 1, level, human);
}
}
}
pub fn get_size_text(size: f64, human: bool) -> String {
if human {
return super::size::human_size(size, 1000f64);
}
return format!("{}", size);
}
|
use std::{fs, collections::BTreeSet};
fn main() {
let input = fs::read_to_string("./input.txt").unwrap_or_default();
let mut unique_houses: BTreeSet<(i32, i32)> = BTreeSet::new();
unique_houses.insert((0,0));
let mut x_santa = 0;
let mut y_santa = 0;
let mut x_robot = 0;
let mut y_robot = 0;
for (index, direction) in input.chars().enumerate() {
if index % 2 == 0 {
match direction {
'^' => y_santa -= 1,
'v' => y_santa += 1,
'<' => x_santa -= 1,
'>' => x_santa += 1,
_ => (),
}
unique_houses.insert((x_santa, y_santa));
} else {
match direction {
'^' => y_robot -= 1,
'v' => y_robot += 1,
'<' => x_robot -= 1,
'>' => x_robot += 1,
_ => (),
}
unique_houses.insert((x_robot, y_robot));
}
}
dbg!(unique_houses.len());
}
|
use mongodb::Database;
use serde::Deserialize;
use std::sync::Arc;
use warp::http::StatusCode;
use crate::user::{User, UserError};
#[derive(Deserialize)]
pub struct UserParams {
username: String,
password: String,
}
pub async fn register(
params: UserParams,
db: Arc<Database>,
) -> Result<impl warp::Reply, warp::Rejection> {
// TODO: check for existing username
let user = match User::new(¶ms.username, ¶ms.password) {
Ok(user) => user,
_ => return Ok(StatusCode::INTERNAL_SERVER_ERROR),
};
if user.save(&db).is_err() {
return Ok(StatusCode::INTERNAL_SERVER_ERROR);
}
Ok(StatusCode::OK)
}
pub async fn login(
params: UserParams,
db: Arc<Database>,
) -> Result<impl warp::Reply, warp::Rejection> {
let _user = match User::login(&db, ¶ms.username, ¶ms.password) {
Ok(user) => user,
Err(UserError::NotFound) => return Ok(StatusCode::UNAUTHORIZED),
_ => return Ok(StatusCode::INTERNAL_SERVER_ERROR),
};
Ok(StatusCode::OK)
}
pub async fn logout() -> Result<impl warp::Reply, warp::Rejection> {
Ok(StatusCode::OK)
}
|
use crate::*;
static PACKAGE_NAME_VERSION_DELIMETER: &str = "@";
pub type PackageNameVersion = String;
#[derive(BorshDeserialize, BorshSerialize)]
pub struct Package {
pub src_hash: String,
pub urls: Vec<String>,
}
#[derive(Serialize, Deserialize)]
#[serde(crate = "near_sdk::serde")]
pub struct PackageJson {
pub name_version: PackageNameVersion,
pub src_hash: String,
pub urls: Vec<String>,
}
#[near_bindgen]
impl Contract {
#[payable]
pub fn add_package(
&mut self,
name_version: PackageNameVersion,
src_hash: String,
urls: Vec<String>,
) {
assert_at_least_one_yocto();
assert!(name_version.contains(PACKAGE_NAME_VERSION_DELIMETER), "Package name_version must be <package>@<version>");
let mut name_version_split = name_version.split(PACKAGE_NAME_VERSION_DELIMETER);
assert!(!name_version_split.next().unwrap().is_empty(), "Must specify a package name");
assert!(!name_version_split.next().unwrap().is_empty(), "Must specify a package version");
let initial_storage_usage = env::storage_usage();
self.packages_by_name_version.insert(&name_version, &Package {
src_hash,
urls,
});
refund_deposit(initial_storage_usage, env::storage_usage(), None);
}
#[payable]
pub fn add_mirrors(
&mut self,
name_version: PackageNameVersion,
urls: Vec<String>,
) {
assert_at_least_one_yocto();
let initial_storage_usage = env::storage_usage();
let mut package = self.packages_by_name_version.get(&name_version).unwrap_or_else(|| panic!("No package {}", name_version));
package.urls.extend(urls);
refund_deposit(initial_storage_usage, env::storage_usage(), None);
}
/// views
pub fn get_package(
&self,
name_version: PackageNameVersion,
) -> PackageJson {
let Package {
src_hash,
urls,
} = self.packages_by_name_version.get(&name_version).unwrap_or_else(|| panic!("No package {}", name_version));
PackageJson{
name_version,
src_hash,
urls,
}
}
pub fn get_package_range(
&self,
from_index: U64,
limit: u64,
) -> Vec<PackageJson> {
let mut tmp = vec![];
let keys = self.packages_by_name_version.keys_as_vector();
let start = u64::from(from_index);
let end = min(start + limit, keys.len());
for i in start..end {
let name_version = keys.get(i).unwrap();
let Package {
src_hash,
urls,
} = self.packages_by_name_version.get(&name_version).unwrap();
tmp.push(PackageJson{
name_version,
src_hash,
urls,
});
}
tmp
}
}
|
#[doc = "Register `GPIOB_OTYPER` reader"]
pub type R = crate::R<GPIOB_OTYPER_SPEC>;
#[doc = "Register `GPIOB_OTYPER` writer"]
pub type W = crate::W<GPIOB_OTYPER_SPEC>;
#[doc = "Field `OT0` reader - OT0"]
pub type OT0_R = crate::BitReader;
#[doc = "Field `OT0` writer - OT0"]
pub type OT0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OT1` reader - OT1"]
pub type OT1_R = crate::BitReader;
#[doc = "Field `OT1` writer - OT1"]
pub type OT1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OT2` reader - OT2"]
pub type OT2_R = crate::BitReader;
#[doc = "Field `OT2` writer - OT2"]
pub type OT2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OT3` reader - OT3"]
pub type OT3_R = crate::BitReader;
#[doc = "Field `OT3` writer - OT3"]
pub type OT3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OT4` reader - OT4"]
pub type OT4_R = crate::BitReader;
#[doc = "Field `OT4` writer - OT4"]
pub type OT4_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OT5` reader - OT5"]
pub type OT5_R = crate::BitReader;
#[doc = "Field `OT5` writer - OT5"]
pub type OT5_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OT6` reader - OT6"]
pub type OT6_R = crate::BitReader;
#[doc = "Field `OT6` writer - OT6"]
pub type OT6_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OT7` reader - OT7"]
pub type OT7_R = crate::BitReader;
#[doc = "Field `OT7` writer - OT7"]
pub type OT7_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OT8` reader - OT8"]
pub type OT8_R = crate::BitReader;
#[doc = "Field `OT8` writer - OT8"]
pub type OT8_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OT9` reader - OT9"]
pub type OT9_R = crate::BitReader;
#[doc = "Field `OT9` writer - OT9"]
pub type OT9_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OT10` reader - OT10"]
pub type OT10_R = crate::BitReader;
#[doc = "Field `OT10` writer - OT10"]
pub type OT10_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OT11` reader - OT11"]
pub type OT11_R = crate::BitReader;
#[doc = "Field `OT11` writer - OT11"]
pub type OT11_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OT12` reader - OT12"]
pub type OT12_R = crate::BitReader;
#[doc = "Field `OT12` writer - OT12"]
pub type OT12_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OT13` reader - OT13"]
pub type OT13_R = crate::BitReader;
#[doc = "Field `OT13` writer - OT13"]
pub type OT13_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OT14` reader - OT14"]
pub type OT14_R = crate::BitReader;
#[doc = "Field `OT14` writer - OT14"]
pub type OT14_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `OT15` reader - OT15"]
pub type OT15_R = crate::BitReader;
#[doc = "Field `OT15` writer - OT15"]
pub type OT15_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
impl R {
#[doc = "Bit 0 - OT0"]
#[inline(always)]
pub fn ot0(&self) -> OT0_R {
OT0_R::new((self.bits & 1) != 0)
}
#[doc = "Bit 1 - OT1"]
#[inline(always)]
pub fn ot1(&self) -> OT1_R {
OT1_R::new(((self.bits >> 1) & 1) != 0)
}
#[doc = "Bit 2 - OT2"]
#[inline(always)]
pub fn ot2(&self) -> OT2_R {
OT2_R::new(((self.bits >> 2) & 1) != 0)
}
#[doc = "Bit 3 - OT3"]
#[inline(always)]
pub fn ot3(&self) -> OT3_R {
OT3_R::new(((self.bits >> 3) & 1) != 0)
}
#[doc = "Bit 4 - OT4"]
#[inline(always)]
pub fn ot4(&self) -> OT4_R {
OT4_R::new(((self.bits >> 4) & 1) != 0)
}
#[doc = "Bit 5 - OT5"]
#[inline(always)]
pub fn ot5(&self) -> OT5_R {
OT5_R::new(((self.bits >> 5) & 1) != 0)
}
#[doc = "Bit 6 - OT6"]
#[inline(always)]
pub fn ot6(&self) -> OT6_R {
OT6_R::new(((self.bits >> 6) & 1) != 0)
}
#[doc = "Bit 7 - OT7"]
#[inline(always)]
pub fn ot7(&self) -> OT7_R {
OT7_R::new(((self.bits >> 7) & 1) != 0)
}
#[doc = "Bit 8 - OT8"]
#[inline(always)]
pub fn ot8(&self) -> OT8_R {
OT8_R::new(((self.bits >> 8) & 1) != 0)
}
#[doc = "Bit 9 - OT9"]
#[inline(always)]
pub fn ot9(&self) -> OT9_R {
OT9_R::new(((self.bits >> 9) & 1) != 0)
}
#[doc = "Bit 10 - OT10"]
#[inline(always)]
pub fn ot10(&self) -> OT10_R {
OT10_R::new(((self.bits >> 10) & 1) != 0)
}
#[doc = "Bit 11 - OT11"]
#[inline(always)]
pub fn ot11(&self) -> OT11_R {
OT11_R::new(((self.bits >> 11) & 1) != 0)
}
#[doc = "Bit 12 - OT12"]
#[inline(always)]
pub fn ot12(&self) -> OT12_R {
OT12_R::new(((self.bits >> 12) & 1) != 0)
}
#[doc = "Bit 13 - OT13"]
#[inline(always)]
pub fn ot13(&self) -> OT13_R {
OT13_R::new(((self.bits >> 13) & 1) != 0)
}
#[doc = "Bit 14 - OT14"]
#[inline(always)]
pub fn ot14(&self) -> OT14_R {
OT14_R::new(((self.bits >> 14) & 1) != 0)
}
#[doc = "Bit 15 - OT15"]
#[inline(always)]
pub fn ot15(&self) -> OT15_R {
OT15_R::new(((self.bits >> 15) & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - OT0"]
#[inline(always)]
#[must_use]
pub fn ot0(&mut self) -> OT0_W<GPIOB_OTYPER_SPEC, 0> {
OT0_W::new(self)
}
#[doc = "Bit 1 - OT1"]
#[inline(always)]
#[must_use]
pub fn ot1(&mut self) -> OT1_W<GPIOB_OTYPER_SPEC, 1> {
OT1_W::new(self)
}
#[doc = "Bit 2 - OT2"]
#[inline(always)]
#[must_use]
pub fn ot2(&mut self) -> OT2_W<GPIOB_OTYPER_SPEC, 2> {
OT2_W::new(self)
}
#[doc = "Bit 3 - OT3"]
#[inline(always)]
#[must_use]
pub fn ot3(&mut self) -> OT3_W<GPIOB_OTYPER_SPEC, 3> {
OT3_W::new(self)
}
#[doc = "Bit 4 - OT4"]
#[inline(always)]
#[must_use]
pub fn ot4(&mut self) -> OT4_W<GPIOB_OTYPER_SPEC, 4> {
OT4_W::new(self)
}
#[doc = "Bit 5 - OT5"]
#[inline(always)]
#[must_use]
pub fn ot5(&mut self) -> OT5_W<GPIOB_OTYPER_SPEC, 5> {
OT5_W::new(self)
}
#[doc = "Bit 6 - OT6"]
#[inline(always)]
#[must_use]
pub fn ot6(&mut self) -> OT6_W<GPIOB_OTYPER_SPEC, 6> {
OT6_W::new(self)
}
#[doc = "Bit 7 - OT7"]
#[inline(always)]
#[must_use]
pub fn ot7(&mut self) -> OT7_W<GPIOB_OTYPER_SPEC, 7> {
OT7_W::new(self)
}
#[doc = "Bit 8 - OT8"]
#[inline(always)]
#[must_use]
pub fn ot8(&mut self) -> OT8_W<GPIOB_OTYPER_SPEC, 8> {
OT8_W::new(self)
}
#[doc = "Bit 9 - OT9"]
#[inline(always)]
#[must_use]
pub fn ot9(&mut self) -> OT9_W<GPIOB_OTYPER_SPEC, 9> {
OT9_W::new(self)
}
#[doc = "Bit 10 - OT10"]
#[inline(always)]
#[must_use]
pub fn ot10(&mut self) -> OT10_W<GPIOB_OTYPER_SPEC, 10> {
OT10_W::new(self)
}
#[doc = "Bit 11 - OT11"]
#[inline(always)]
#[must_use]
pub fn ot11(&mut self) -> OT11_W<GPIOB_OTYPER_SPEC, 11> {
OT11_W::new(self)
}
#[doc = "Bit 12 - OT12"]
#[inline(always)]
#[must_use]
pub fn ot12(&mut self) -> OT12_W<GPIOB_OTYPER_SPEC, 12> {
OT12_W::new(self)
}
#[doc = "Bit 13 - OT13"]
#[inline(always)]
#[must_use]
pub fn ot13(&mut self) -> OT13_W<GPIOB_OTYPER_SPEC, 13> {
OT13_W::new(self)
}
#[doc = "Bit 14 - OT14"]
#[inline(always)]
#[must_use]
pub fn ot14(&mut self) -> OT14_W<GPIOB_OTYPER_SPEC, 14> {
OT14_W::new(self)
}
#[doc = "Bit 15 - OT15"]
#[inline(always)]
#[must_use]
pub fn ot15(&mut self) -> OT15_W<GPIOB_OTYPER_SPEC, 15> {
OT15_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "GPIO port output type register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gpiob_otyper::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`gpiob_otyper::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct GPIOB_OTYPER_SPEC;
impl crate::RegisterSpec for GPIOB_OTYPER_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`gpiob_otyper::R`](R) reader structure"]
impl crate::Readable for GPIOB_OTYPER_SPEC {}
#[doc = "`write(|w| ..)` method takes [`gpiob_otyper::W`](W) writer structure"]
impl crate::Writable for GPIOB_OTYPER_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets GPIOB_OTYPER to value 0"]
impl crate::Resettable for GPIOB_OTYPER_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use std::collections::HashMap;
/// A parser to parse JSON from string written with top-down parsing method.
use crate::lexer::{generate_tokens, Token, TokenType};
#[derive(Debug, PartialEq)]
pub enum Value {
Null,
Bool(bool),
Number(f64),
String(String),
Array(Vec<Value>),
Object(HashMap<String, Value>),
}
pub fn parse(s: &str) -> Result<Value, &'static str> {
// first tokenize the string into tokens
let tokens = generate_tokens(s);
// then construct the Json value from the tokens.
let (value, tokens) = parse_value(&tokens)?;
if !tokens.is_empty() {
return Err("trailing string after json.");
}
Ok(value)
}
// construct a value from the tokens and return the value and any left tokens.
fn parse_value<'a, 'b>(tokens: &'a [Token<'b>]) -> Result<(Value, &'a [Token<'b>]), &'static str> {
if tokens.is_empty() {
return Ok((Value::String("".to_owned()), tokens));
}
match tokens[0]._type {
TokenType::LeftBracket => parse_object(tokens),
TokenType::LeftSquareBracket => parse_array(tokens),
TokenType::Quote => parse_string(tokens),
TokenType::Null => Ok((Value::Null, &tokens[1..])),
TokenType::Boolean => Ok((Value::Bool(tokens[0].s == "true".as_bytes()), &tokens[1..])),
// if it is number, for simplicity, we use f64 always
TokenType::Number => {
if let Ok(num) = std::str::from_utf8(tokens[0].s).unwrap().parse::<f64>() {
Ok((Value::Number(num), &tokens[1..]))
} else {
Err("cannot parse the string into the numbers.")
}
}
_ => Err("unsupported format."),
}
}
fn parse_object<'a, 'b>(tokens: &'a [Token<'b>]) -> Result<(Value, &'a [Token<'b>]), &'static str> {
if tokens.len() < 2 || tokens[0]._type != TokenType::LeftBracket {
return Err("Not a object.");
}
// empty object
if tokens[1]._type == TokenType::RightBracket {
return Ok((Value::Object(HashMap::new()), &tokens[2..]));
}
let mut m = HashMap::new();
let mut tokens = &tokens[1..];
loop {
if let (Value::String(s), token) = parse_string(tokens)? {
if token[0]._type != TokenType::Colon {
return Err("colon expected.");
}
let (value, token) = parse_value(&token[1..])?;
m.insert(s, value);
// if there is no more key value pair to deal with.
if token[0]._type != TokenType::Comma {
tokens = token;
break;
}
tokens = &token[1..];
}
}
if tokens.is_empty() || tokens[0]._type != TokenType::RightBracket {
return Err("right bracket expected.");
}
Ok((Value::Object(m), &tokens[1..]))
}
fn parse_array<'a, 'b>(tokens: &'a [Token<'b>]) -> Result<(Value, &'a [Token<'b>]), &'static str> {
if tokens.len() < 2 || tokens[0]._type != TokenType::LeftSquareBracket {
return Err("expect array");
}
let mut vec = vec![];
let mut tokens = &tokens[1..];
loop {
if tokens.is_empty() {
return Err("array expected.");
}
if tokens[0]._type == TokenType::RightSquareBracket {
break;
}
let (value, token) = parse_value(tokens)?;
vec.push(value);
if token.is_empty() {
return Err("array expected.");
}
if token[0]._type == TokenType::Comma {
tokens = &token[1..];
} else {
tokens = token;
}
}
Ok((Value::Array(vec), &tokens[1..]))
}
fn parse_string<'a, 'b>(tokens: &'a [Token<'b>]) -> Result<(Value, &'a [Token<'b>]), &'static str> {
if tokens.len() < 3
|| tokens[0]._type != TokenType::Quote
|| tokens[2]._type != TokenType::Quote
|| tokens[1]._type != TokenType::String
{
return Err("expected string");
}
Ok((
Value::String(std::str::from_utf8(tokens[1].s).unwrap().to_owned()),
&tokens[3..],
))
}
#[cfg(test)]
mod test {
use super::*;
use std::collections::HashMap;
#[test]
fn test_parsing() {
{
let v = parse("{}");
let exp = Value::Object(HashMap::new());
assert_eq!(exp, v.unwrap());
}
{
let v = parse(r#"{"key":"value"}"#);
let mut m = HashMap::new();
m.insert("key".to_owned(), Value::String("value".to_owned()));
let exp = Value::Object(m);
assert_eq!(exp, v.unwrap());
}
{
let v = parse(r#"{"key": null}"#);
let mut m = HashMap::new();
m.insert("key".to_owned(), Value::Null);
let exp = Value::Object(m);
assert_eq!(exp, v.unwrap());
}
{
let v = parse(r#"{"key": true }"#);
let mut m = HashMap::new();
m.insert("key".to_owned(), Value::Bool(true));
let exp = Value::Object(m);
assert_eq!(exp, v.unwrap());
}
{
let v = parse(r#"{"key": false }"#);
let mut m = HashMap::new();
m.insert("key".to_owned(), Value::Bool(false));
let exp = Value::Object(m);
assert_eq!(exp, v.unwrap());
}
{
let v = parse(r#"{"key": false , "k2": "v2" }"#);
let mut m = HashMap::new();
m.insert("key".to_owned(), Value::Bool(false));
m.insert("k2".to_owned(), Value::String("v2".to_owned()));
let exp = Value::Object(m);
assert_eq!(exp, v.unwrap());
}
{
let v = parse(r#"{"key": false , "k2": {"k3": null} }"#);
let mut m = HashMap::new();
m.insert("key".to_owned(), Value::Bool(false));
let mut nm = HashMap::new();
nm.insert("k3".to_owned(), Value::Null);
m.insert("k2".to_owned(), Value::Object(nm));
let exp = Value::Object(m);
assert_eq!(exp, v.unwrap());
}
{
let v = parse(r#"[]"#);
let vec = vec![];
let exp = Value::Array(vec);
assert_eq!(exp, v.unwrap());
}
{
let v = parse(r#"[ null ]"#);
let mut vec = vec![];
vec.push(Value::Null);
let exp = Value::Array(vec);
assert_eq!(exp, v.unwrap());
}
{
let v = parse(r#"[ null , false]"#);
let mut vec = vec![];
vec.push(Value::Null);
vec.push(Value::Bool(false));
let exp = Value::Array(vec);
assert_eq!(exp, v.unwrap());
}
{
let v = parse(r#"[ null , false, {"k1": "v2"}]"#);
let mut vec = vec![];
vec.push(Value::Null);
vec.push(Value::Bool(false));
let mut m = HashMap::new();
m.insert("k1".to_owned(), Value::String("v2".to_owned()));
vec.push(Value::Object(m));
let exp = Value::Array(vec);
assert_eq!(exp, v.unwrap());
}
{
let v = parse(r#"[ null , false, {"k1": "v2"}, "ss"]"#);
let mut vec = vec![];
vec.push(Value::Null);
vec.push(Value::Bool(false));
let mut m = HashMap::new();
m.insert("k1".to_owned(), Value::String("v2".to_owned()));
vec.push(Value::Object(m));
vec.push(Value::String("ss".to_owned()));
let exp = Value::Array(vec);
assert_eq!(exp, v.unwrap());
}
{
let v = parse(r#"{ "kk": [ null , false, {"k1": "v2"}, "ss"]}"#);
let mut vec = vec![];
vec.push(Value::Null);
vec.push(Value::Bool(false));
let mut m = HashMap::new();
m.insert("k1".to_owned(), Value::String("v2".to_owned()));
vec.push(Value::Object(m));
vec.push(Value::String("ss".to_owned()));
let mut mo = HashMap::new();
mo.insert("kk".to_owned(), Value::Array(vec));
let exp = Value::Object(mo);
assert_eq!(exp, v.unwrap());
}
{
let v = parse(r#"{"key":345}"#);
let mut m = HashMap::new();
m.insert("key".to_owned(), Value::Number(345.0));
let exp = Value::Object(m);
assert_eq!(exp, v.unwrap());
}
{
let v = parse(r#"{"key":345, "k2": [123, true]}"#);
let mut m = HashMap::new();
m.insert("key".to_owned(), Value::Number(345.0));
let mut vec = vec![];
vec.push(Value::Number(123.0));
vec.push(Value::Bool(true));
m.insert("k2".to_owned(), Value::Array(vec));
let exp = Value::Object(m);
assert_eq!(exp, v.unwrap());
}
{
let v = parse(r#"{"key":345, "k2": [123e2, true]}"#);
let mut m = HashMap::new();
m.insert("key".to_owned(), Value::Number(345.0));
let mut vec = vec![];
vec.push(Value::Number(123e2));
vec.push(Value::Bool(true));
m.insert("k2".to_owned(), Value::Array(vec));
let exp = Value::Object(m);
assert_eq!(exp, v.unwrap());
}
}
}
|
#![feature(inclusive_range_syntax)]
#![feature(step_by)]
#![crate_type = "cdylib"]
#[no_mangle]
pub extern "C" fn is_prime(n: u32) -> bool {
match n {
0 | 1 => false,
2 | 3 => true,
n if n & 1 == 0 => false, // even numbers
n => {
let limit = (n as f32).sqrt() as u32 + 1;
for i in (4...limit).step_by(2) {
if n % i == 0 {
return false;
}
}
return true;
}
}
}
#[no_mangle]
pub extern "C" fn spare() {
println!("");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prime_tester_works() {
let primes = vec![2, 3, 5, 7, 11, 13, 17, 19];
for prime in primes {
assert!(is_prime(prime));
}
let not_primes = vec![0, 1, 4, 10, 22];
for num in not_primes {
assert!(!is_prime(num));
}
}
}
|
use super::codegen::ContextKind;
use crate::*;
#[cfg(feature = "perf")]
use super::perf::*;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, SyncSender};
use vm_inst::*;
pub type ValueTable = HashMap<IdentId, Value>;
pub type VMResult = Result<Value, RubyError>;
#[derive(Debug)]
pub struct VM {
// Global info
pub globals: GlobalsRef,
pub root_path: Vec<PathBuf>,
// VM state
fiber_state: FiberState,
exec_context: Vec<ContextRef>,
class_context: Vec<(Value, DefineMode)>,
exec_stack: Vec<Value>,
exception: bool,
pc: usize,
pub channel: Option<(SyncSender<VMResult>, Receiver<usize>)>,
#[cfg(feature = "perf")]
perf: Perf,
}
pub type VMRef = Ref<VM>;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum FiberState {
Created,
Running,
Dead,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DefineMode {
module_function: bool,
}
impl DefineMode {
pub fn default() -> Self {
DefineMode {
module_function: false,
}
}
}
// API's
impl VM {
pub fn new() -> Self {
use builtin::*;
let mut globals = Globals::new();
macro_rules! set_builtin_class {
($name:expr, $class_object:ident) => {
let id = globals.get_ident_id($name);
globals
.builtins
.object
.set_var(id, globals.builtins.$class_object);
};
}
macro_rules! set_class {
($name:expr, $class_object:expr) => {
let id = globals.get_ident_id($name);
let object = $class_object;
globals.builtins.object.set_var(id, object);
};
}
set_builtin_class!("Object", object);
set_builtin_class!("Module", module);
set_builtin_class!("Class", class);
set_builtin_class!("Integer", integer);
set_builtin_class!("Float", float);
set_builtin_class!("Array", array);
set_builtin_class!("Proc", procobj);
set_builtin_class!("Range", range);
set_builtin_class!("String", string);
set_builtin_class!("Hash", hash);
set_builtin_class!("Method", method);
set_builtin_class!("Regexp", regexp);
set_builtin_class!("Fiber", fiber);
set_builtin_class!("Enumerator", enumerator);
set_class!("Math", math::init_math(&mut globals));
set_class!("File", file::init_file(&mut globals));
set_class!("Process", process::init_process(&mut globals));
set_class!("Struct", structobj::init_struct(&mut globals));
set_class!("StandardError", Value::class(&globals, globals.class_class));
set_class!("RuntimeError", errorobj::init_error(&mut globals));
let vm = VM {
globals: GlobalsRef::new(globals),
root_path: vec![],
fiber_state: FiberState::Created,
class_context: vec![(Value::nil(), DefineMode::default())],
exec_context: vec![],
exec_stack: vec![],
exception: false,
pc: 0,
channel: None,
#[cfg(feature = "perf")]
perf: Perf::new(),
};
vm
}
pub fn dup_fiber(&self, tx: SyncSender<VMResult>, rx: Receiver<usize>) -> Self {
VM {
globals: self.globals.clone(),
root_path: self.root_path.clone(),
fiber_state: FiberState::Created,
exec_context: vec![],
class_context: self.class_context.clone(),
exec_stack: vec![],
exception: false,
pc: 0,
channel: Some((tx, rx)),
#[cfg(feature = "perf")]
perf: self.perf.clone(),
}
}
pub fn context(&self) -> ContextRef {
*self.exec_context.last().unwrap()
}
pub fn caller_context(&self) -> ContextRef {
let len = self.exec_context.len();
if len < 2 {
unreachable!("caller_context(): exec_context.len is {}", len)
};
self.exec_context[len - 2]
}
pub fn source_info(&self) -> SourceInfoRef {
self.context().iseq_ref.source_info
}
pub fn fiberstate_created(&mut self) {
self.fiber_state = FiberState::Created;
}
pub fn fiberstate_running(&mut self) {
self.fiber_state = FiberState::Running;
}
pub fn fiberstate_dead(&mut self) {
self.fiber_state = FiberState::Dead;
}
pub fn fiberstate(&self) -> FiberState {
self.fiber_state
}
pub fn stack_push(&mut self, val: Value) {
self.exec_stack.push(val)
}
pub fn stack_pop(&mut self) -> Value {
self.exec_stack.pop().unwrap()
}
pub fn context_push(&mut self, ctx: ContextRef) {
self.exec_context.push(ctx);
}
pub fn context_pop(&mut self) -> Option<ContextRef> {
self.exec_context.pop()
}
pub fn clear(&mut self) {
self.exec_stack.clear();
self.class_context = vec![(Value::nil(), DefineMode::default())];
self.exec_context.clear();
}
pub fn class_push(&mut self, val: Value) {
self.class_context.push((val, DefineMode::default()));
}
pub fn class_pop(&mut self) {
self.class_context.pop().unwrap();
}
pub fn classref(&self) -> ClassRef {
let (class, _) = self.class_context.last().unwrap();
if class.is_nil() {
self.globals.object_class
} else {
class.as_module().unwrap()
}
}
pub fn class(&self) -> Value {
let (class, _) = self.class_context.last().unwrap();
if class.is_nil() {
self.globals.builtins.object
} else {
*class
}
}
pub fn define_mode(&self) -> &DefineMode {
&self.class_context.last().unwrap().1
}
pub fn define_mode_mut(&mut self) -> &mut DefineMode {
&mut self.class_context.last_mut().unwrap().1
}
pub fn module_function(&mut self, flag: bool) {
self.class_context.last_mut().unwrap().1.module_function = flag;
}
pub fn get_pc(&mut self) -> usize {
self.pc
}
pub fn set_pc(&mut self, pc: usize) {
self.pc = pc;
}
pub fn jump_pc(&mut self, inst_offset: i64, disp: i64) {
self.pc = ((self.pc as i64) + inst_offset + disp) as usize;
}
fn read16(&self, iseq: &ISeq, offset: usize) -> u16 {
let pc = self.pc + offset;
let ptr = iseq[pc..pc + 1].as_ptr() as *const u16;
unsafe { *ptr }
}
fn read32(&self, iseq: &ISeq, offset: usize) -> u32 {
let pc = self.pc + offset;
let ptr = iseq[pc..pc + 1].as_ptr() as *const u32;
unsafe { *ptr }
}
fn read_usize(&self, iseq: &ISeq, offset: usize) -> usize {
self.read32(iseq, offset) as usize
}
fn read_id(&self, iseq: &ISeq, offset: usize) -> IdentId {
IdentId::from(self.read32(iseq, offset))
}
fn read_lvar_id(&self, iseq: &ISeq, offset: usize) -> LvarId {
LvarId::from_usize(self.read_usize(iseq, offset))
}
fn read_methodref(&self, iseq: &ISeq, offset: usize) -> MethodRef {
MethodRef::from(self.read32(iseq, offset))
}
fn read64(&self, iseq: &ISeq, offset: usize) -> u64 {
let pc = self.pc + offset;
let ptr = iseq[pc..pc + 1].as_ptr() as *const u64;
unsafe { *ptr }
}
fn read8(&self, iseq: &ISeq, offset: usize) -> u8 {
iseq[self.pc + offset]
}
fn read_disp(&self, iseq: &ISeq, offset: usize) -> i64 {
self.read32(iseq, offset) as i32 as i64
}
pub fn parse_program(&mut self, path: PathBuf, program: &str) -> Result<MethodRef, RubyError> {
let mut parser = Parser::new();
std::mem::swap(&mut parser.ident_table, &mut self.globals.ident_table);
let result = parser.parse_program(path, program)?;
self.globals.ident_table = result.ident_table;
#[cfg(feature = "perf")]
{
self.perf.set_prev_inst(Perf::INVALID);
}
let methodref = Codegen::new(result.source_info).gen_iseq(
&mut self.globals,
&vec![],
&result.node,
&result.lvar_collector,
true,
ContextKind::Method,
None,
)?;
Ok(methodref)
}
pub fn parse_program_eval(
&mut self,
path: PathBuf,
program: &str,
) -> Result<MethodRef, RubyError> {
let mut parser = Parser::new();
std::mem::swap(&mut parser.ident_table, &mut self.globals.ident_table);
let ext_lvar = self.context().iseq_ref.lvar.clone();
let result = parser.parse_program_eval(path, program, ext_lvar.clone())?;
self.globals.ident_table = result.ident_table;
#[cfg(feature = "perf")]
{
self.perf.set_prev_inst(Perf::INVALID);
}
let mut codegen = Codegen::new(result.source_info);
codegen.context_push(ext_lvar);
let method = codegen.gen_iseq(
&mut self.globals,
&vec![],
&result.node,
&result.lvar_collector,
true,
ContextKind::Eval,
None,
)?;
Ok(method)
}
pub fn run(&mut self, path: PathBuf, program: &str, self_value: Option<Value>) -> VMResult {
let method = self.parse_program(path, program)?;
let self_value = match self_value {
Some(val) => val,
None => self.globals.main_object,
};
let arg = Args::new0();
let val = self.eval_send(method, self_value, &arg)?;
#[cfg(feature = "perf")]
{
self.perf.get_perf(Perf::INVALID);
}
let stack_len = self.exec_stack.len();
if stack_len != 0 {
eprintln!("Error: stack length is illegal. {}", stack_len);
};
#[cfg(feature = "perf")]
{
self.perf.print_perf();
}
Ok(val)
}
pub fn run_repl(&mut self, result: &ParseResult, mut context: ContextRef) -> VMResult {
#[cfg(feature = "perf")]
{
self.perf.set_prev_inst(Perf::CODEGEN);
}
self.globals.ident_table = result.ident_table.clone();
let methodref = Codegen::new(result.source_info).gen_iseq(
&mut self.globals,
&vec![],
&result.node,
&result.lvar_collector,
true,
ContextKind::Method,
None,
)?;
let iseq = self.get_iseq(methodref)?;
context.iseq_ref = iseq;
context.adjust_lvar_size();
context.pc = 0;
let val = self.run_context(context)?;
#[cfg(feature = "perf")]
{
self.perf.get_perf(Perf::INVALID);
}
let stack_len = self.exec_stack.len();
if stack_len != 0 {
eprintln!("Error: stack length is illegal. {}", stack_len);
};
#[cfg(feature = "perf")]
{
self.perf.print_perf();
}
Ok(val)
}
}
macro_rules! try_err {
($self:ident, $eval:expr) => {
match $eval {
Ok(val) => $self.stack_push(val),
Err(err) if err.kind == RubyErrorKind::BlockReturn => {}
Err(mut err) => {
let m = $self.context().iseq_ref.method;
let res = if RubyErrorKind::MethodReturn(m) == err.kind {
let result = $self.stack_pop();
let prev_len = $self.context().stack_len;
$self.exec_stack.truncate(prev_len);
$self.unwind_context(&mut err);
#[cfg(feature = "trace")]
{
println!("<--- METHOD_RETURN Ok({})", $self.val_inspect(result),);
}
Ok(result)
} else {
$self.unwind_context(&mut err);
#[cfg(feature = "trace")]
{
println!("<--- Err({:?})", err.kind);
}
Err(err)
};
$self.fiberstate_dead();
$self.fiber_send_to_parent(res.clone());
return res;
}
};
};
}
impl VM {
/// Main routine for VM execution.
pub fn run_context(&mut self, context: ContextRef) -> VMResult {
#[cfg(feature = "trace")]
{
if context.is_fiber {
println!("===> {:?}", context.iseq_ref.method);
} else {
println!("---> {:?}", context.iseq_ref.method);
}
}
if let Some(prev_context) = self.exec_context.last_mut() {
prev_context.pc = self.pc;
prev_context.stack_len = self.exec_stack.len();
};
self.context_push(context);
self.pc = context.pc;
let iseq = &context.iseq_ref.iseq;
let mut self_oref = context.self_value.as_object();
loop {
#[cfg(feature = "perf")]
{
self.perf.get_perf(iseq[self.pc]);
}
#[cfg(feature = "trace")]
{
println!(
"{:>4x}:{:<15} stack:{}",
self.pc,
Inst::inst_name(iseq[self.pc]),
self.exec_stack.len()
);
}
match iseq[self.pc] {
Inst::END => {
// reached the end of the method or block.
// - the end of the method or block.
// - `next` in block AND outer of loops.
if self.exec_context.len() == 1 {
// if in the final context, the fiber becomes DEAD.
self.fiberstate_dead();
self.fiber_send_to_parent(Err(self.error_fiber("Dead fiber called.")));
};
let _context = self.context_pop().unwrap();
let val = self.stack_pop();
#[cfg(feature = "trace")]
{
if _context.is_fiber {
println!("<=== Ok({})", self.val_inspect(val));
} else {
println!("<--- Ok({})", self.val_inspect(val));
}
}
if !self.exec_context.is_empty() {
self.pc = self.context().pc;
};
return Ok(val);
}
Inst::RETURN => {
// 'Inst::RETURN' is executed.
// - `return` in method.
// - `break` outer of loops.
let res = if let ISeqKind::Block(_) = context.kind {
// if in block context, exit with Err(BLOCK_RETURN).
let err = self.error_block_return();
#[cfg(feature = "trace")]
{
println!("<--- Err({:?})", err.kind);
}
Err(err)
} else {
// if in method context, exit with Ok(rerurn_value).
let val = self.stack_pop();
#[cfg(feature = "trace")]
{
println!("<--- Ok({})", self.val_inspect(val));
}
Ok(val)
};
self.context_pop().unwrap();
if !self.exec_context.is_empty() {
self.pc = self.context().pc;
}
return res;
}
Inst::MRETURN => {
// 'METHOD_RETURN' is executed.
// - `return` in block
let res = if let ISeqKind::Block(method) = context.kind {
// exit with Err(METHOD_RETURN).
let err = self.error_method_return(method);
#[cfg(feature = "trace")]
{
println!("<--- Err({:?})", err.kind);
}
Err(err)
} else {
unreachable!()
};
self.context_pop().unwrap();
if !self.exec_context.is_empty() {
self.pc = self.context().pc;
}
return res;
}
Inst::PUSH_NIL => {
self.stack_push(Value::nil());
self.pc += 1;
}
Inst::PUSH_TRUE => {
self.stack_push(Value::true_val());
self.pc += 1;
}
Inst::PUSH_FALSE => {
self.stack_push(Value::false_val());
self.pc += 1;
}
Inst::PUSH_SELF => {
self.stack_push(context.self_value);
self.pc += 1;
}
Inst::PUSH_FIXNUM => {
let num = self.read64(iseq, 1);
self.pc += 9;
self.stack_push(Value::fixnum(num as i64));
}
Inst::PUSH_FLONUM => {
let num = f64::from_bits(self.read64(iseq, 1));
self.pc += 9;
self.stack_push(Value::flonum(num));
}
Inst::PUSH_STRING => {
let id = self.read_id(iseq, 1);
let string = self.globals.get_ident_name(id).to_string();
self.stack_push(Value::string(&self.globals, string));
self.pc += 5;
}
Inst::PUSH_SYMBOL => {
let id = self.read_id(iseq, 1);
self.stack_push(Value::symbol(id));
self.pc += 5;
}
Inst::ADD => {
let lhs = self.stack_pop();
let rhs = self.stack_pop();
try_err!(self, self.eval_add(lhs, rhs, iseq));
self.pc += 5;
}
Inst::ADDI => {
let lhs = self.stack_pop();
let i = self.read32(iseq, 1) as i32;
let val = self.eval_addi(lhs, i)?;
self.stack_push(val);
self.pc += 5;
}
Inst::SUB => {
let lhs = self.stack_pop();
let rhs = self.stack_pop();
try_err!(self, self.eval_sub(lhs, rhs, iseq));
self.pc += 5;
}
Inst::SUBI => {
let lhs = self.stack_pop();
let i = self.read32(iseq, 1) as i32;
let val = self.eval_subi(lhs, i)?;
self.stack_push(val);
self.pc += 5;
}
Inst::MUL => {
let lhs = self.stack_pop();
let rhs = self.stack_pop();
let val = self.eval_mul(lhs, rhs, iseq)?;
self.stack_push(val);
self.pc += 5;
}
Inst::POW => {
let lhs = self.stack_pop();
let rhs = self.stack_pop();
let val = self.eval_exp(lhs, rhs)?;
self.stack_push(val);
self.pc += 1;
}
Inst::DIV => {
let lhs = self.stack_pop();
let rhs = self.stack_pop();
let val = self.eval_div(lhs, rhs)?;
self.stack_push(val);
self.pc += 1;
}
Inst::REM => {
let lhs = self.stack_pop();
let rhs = self.stack_pop();
let val = self.eval_rem(lhs, rhs)?;
self.stack_push(val);
self.pc += 1;
}
Inst::SHR => {
let lhs = self.stack_pop();
let rhs = self.stack_pop();
let val = self.eval_shr(lhs, rhs)?;
self.stack_push(val);
self.pc += 1;
}
Inst::SHL => {
let lhs = self.stack_pop();
let rhs = self.stack_pop();
let val = self.eval_shl(lhs, rhs, iseq)?;
self.stack_push(val);
self.pc += 5;
}
Inst::BIT_AND => {
let lhs = self.stack_pop();
let rhs = self.stack_pop();
let val = self.eval_bitand(lhs, rhs)?;
self.stack_push(val);
self.pc += 1;
}
Inst::BIT_OR => {
let lhs = self.stack_pop();
let rhs = self.stack_pop();
let val = self.eval_bitor(lhs, rhs)?;
self.stack_push(val);
self.pc += 1;
}
Inst::BIT_XOR => {
let lhs = self.stack_pop();
let rhs = self.stack_pop();
let val = self.eval_bitxor(lhs, rhs)?;
self.stack_push(val);
self.pc += 1;
}
Inst::BIT_NOT => {
let lhs = self.stack_pop();
let val = self.eval_bitnot(lhs)?;
self.stack_push(val);
self.pc += 1;
}
Inst::EQ => {
let lhs = self.stack_pop();
let rhs = self.stack_pop();
let val = Value::bool(self.eval_eq(rhs, lhs)?);
self.stack_push(val);
self.pc += 1;
}
Inst::NE => {
let lhs = self.stack_pop();
let rhs = self.stack_pop();
let val = Value::bool(!self.eval_eq(rhs, lhs)?);
self.stack_push(val);
self.pc += 1;
}
Inst::TEQ => {
let lhs = self.stack_pop();
let rhs = self.stack_pop();
let res = self.eval_teq(rhs, lhs)?;
let val = Value::bool(res);
self.stack_push(val);
self.pc += 1;
}
Inst::GT => {
let lhs = self.stack_pop();
let rhs = self.stack_pop();
let val = self.eval_gt(lhs, rhs)?;
self.stack_push(val);
self.pc += 1;
}
Inst::GE => {
let lhs = self.stack_pop();
let rhs = self.stack_pop();
let val = self.eval_ge(lhs, rhs)?;
self.stack_push(val);
self.pc += 1;
}
Inst::CMP => {
let lhs = self.stack_pop();
let rhs = self.stack_pop();
let val = self.eval_cmp(rhs, lhs)?;
self.stack_push(val);
self.pc += 1;
}
Inst::NOT => {
let lhs = self.stack_pop();
let val = Value::bool(!self.val_to_bool(lhs));
self.stack_push(val);
self.pc += 1;
}
Inst::CONCAT_STRING => {
let rhs = self.stack_pop();
let lhs = self.stack_pop();
let val = match (lhs.as_string(), rhs.as_string()) {
(Some(lhs), Some(rhs)) => {
Value::string(&self.globals, format!("{}{}", lhs, rhs))
}
(_, _) => unreachable!("Illegal CAONCAT_STRING arguments."),
};
self.stack_push(val);
self.pc += 1;
}
Inst::SET_LOCAL => {
let id = self.read_lvar_id(iseq, 1);
let outer = self.read32(iseq, 5);
let val = self.stack_pop();
let mut cref = self.get_outer_context(outer);
cref[id] = val;
self.pc += 9;
}
Inst::GET_LOCAL => {
let id = self.read_lvar_id(iseq, 1);
let outer = self.read32(iseq, 5);
let cref = self.get_outer_context(outer);
let val = cref[id];
self.stack_push(val);
self.pc += 9;
}
Inst::CHECK_LOCAL => {
let id = self.read_lvar_id(iseq, 1);
let outer = self.read32(iseq, 5);
let cref = self.get_outer_context(outer);
let val = cref[id].is_uninitialized();
self.stack_push(Value::bool(val));
self.pc += 9;
}
Inst::SET_CONST => {
let id = self.read_id(iseq, 1);
let mut parent = match self.stack_pop() {
v if v == Value::nil() => self.class(),
v => v,
};
let val = self.stack_pop();
match val.as_module() {
Some(mut cref) => {
if cref.name == None {
cref.name = Some(id);
}
}
None => {}
}
parent.set_var(id, val);
self.pc += 5;
}
Inst::GET_CONST => {
let id = self.read_id(iseq, 1);
let val = match self.get_env_const(id) {
Some(val) => val,
None => self.get_super_const(self.class(), id)?,
};
self.stack_push(val);
self.pc += 5;
}
Inst::GET_CONST_TOP => {
let id = self.read_id(iseq, 1);
let class = self.globals.builtins.object;
let val = self.get_super_const(class, id)?;
self.stack_push(val);
self.pc += 5;
}
Inst::GET_SCOPE => {
let parent = self.stack_pop();
let id = self.read_id(iseq, 1);
let val = self.get_super_const(parent, id)?;
self.stack_push(val);
self.pc += 5;
}
Inst::SET_IVAR => {
let var_id = self.read_id(iseq, 1);
let new_val = self.stack_pop();
self_oref.set_var(var_id, new_val);
self.pc += 5;
}
Inst::GET_IVAR => {
let var_id = self.read_id(iseq, 1);
let val = match self_oref.get_var(var_id) {
Some(val) => val.clone(),
None => Value::nil(),
};
self.stack_push(val);
self.pc += 5;
}
Inst::IVAR_ADDI => {
let var_id = self.read_id(iseq, 1);
let i = self.read32(iseq, 5) as i32;
match self_oref.get_mut_var(var_id) {
Some(val) => {
let new_val = self.eval_addi(*val, i)?;
*val = new_val;
}
None => {
let new_val = self.eval_addi(Value::nil(), i)?;
self_oref.set_var(var_id, new_val);
}
};
self.pc += 9;
}
Inst::SET_GVAR => {
let var_id = self.read_id(iseq, 1);
let new_val = self.stack_pop();
self.set_global_var(var_id, new_val);
self.pc += 5;
}
Inst::GET_GVAR => {
let var_id = self.read_id(iseq, 1);
let val = self.get_global_var(var_id);
self.stack_push(val);
self.pc += 5;
}
Inst::SET_INDEX => {
let arg_num = self.read_usize(iseq, 1);
let mut args = self.pop_args_to_ary(arg_num);
let receiver = self.stack_pop();
let val = self.stack_pop();
match receiver.is_object() {
Some(oref) => {
match &oref.kind {
ObjKind::Array(mut aref) => {
args.push(val);
aref.set_elem(self, &args)?;
}
ObjKind::Hash(mut href) => href.insert(args[0], val),
_ => return Err(self.error_undefined_method("[]=", receiver)),
};
}
None => return Err(self.error_undefined_method("[]=", receiver)),
}
self.pc += 5;
}
Inst::GET_INDEX => {
let arg_num = self.read_usize(iseq, 1);
let args = self.pop_args_to_ary(arg_num);
let arg_num = args.len();
let receiver = self.stack_pop();
let val = match receiver.is_object() {
Some(oref) => match &oref.kind {
ObjKind::Array(aref) => aref.get_elem(self, &args)?,
ObjKind::Hash(href) => {
self.check_args_range(arg_num, 1, 1)?;
match href.get(&args[0]) {
Some(val) => *val,
None => Value::nil(),
}
}
ObjKind::Method(mref) => {
self.eval_send(mref.method, mref.receiver, &args)?
}
_ => {
let id = self.globals.get_ident_id("[]");
match self.get_method(receiver, id) {
Ok(mref) => self.eval_send(mref, receiver, &args)?,
Err(_) => {
return Err(self.error_undefined_method("[]", receiver))
}
}
}
},
None if receiver.is_packed_fixnum() => {
let i = receiver.as_packed_fixnum();
self.check_args_range(arg_num, 1, 1)?;
let index = args[0].expect_integer(&self, "Index")?;
let val = if index < 0 || 63 < index {
0
} else {
(i >> index) & 1
};
Value::fixnum(val)
}
_ => return Err(self.error_undefined_method("[]", receiver)),
};
self.stack_push(val);
self.pc += 5;
}
Inst::SPLAT => {
let val = self.stack_pop();
let res = Value::splat(&self.globals, val);
self.stack_push(res);
self.pc += 1;
}
Inst::CREATE_RANGE => {
let start = self.stack_pop();
let end = self.stack_pop();
if !start.is_packed_fixnum() || !end.is_packed_fixnum() {
return Err(self.error_argument("Bad value for range."));
};
let exclude_val = self.stack_pop();
let exclude_end = self.val_to_bool(exclude_val);
let range = Value::range(&self.globals, start, end, exclude_end);
self.stack_push(range);
self.pc += 1;
}
Inst::CREATE_ARRAY => {
let arg_num = self.read_usize(iseq, 1);
let elems = self.pop_args_to_ary(arg_num).into_vec();
let array = Value::array_from(&self.globals, elems);
self.stack_push(array);
self.pc += 5;
}
Inst::CREATE_PROC => {
let method = self.read_methodref(iseq, 1);
let proc_obj = self.create_proc(method)?;
self.stack_push(proc_obj);
self.pc += 5;
}
Inst::CREATE_HASH => {
let arg_num = self.read_usize(iseq, 1);
let key_value = self.pop_key_value_pair(arg_num);
let hash = Value::hash(&self.globals, HashRef::from(key_value));
self.stack_push(hash);
self.pc += 5;
}
Inst::CREATE_REGEXP => {
let arg = self.stack_pop();
let regexp = self.create_regexp(arg)?;
self.stack_push(regexp);
self.pc += 1;
}
Inst::JMP => {
let disp = self.read_disp(iseq, 1);
self.jump_pc(5, disp);
}
Inst::JMP_IF_FALSE => {
let val = self.stack_pop();
if self.val_to_bool(val) {
self.jump_pc(5, 0);
} else {
let disp = self.read_disp(iseq, 1);
self.jump_pc(5, disp);
}
}
Inst::OPT_CASE => {
let val = self.stack_pop();
let map = self.globals.get_case_dispatch_map(self.read32(iseq, 1));
let disp = match map.get(&val) {
Some(disp) => *disp as i64,
None => self.read_disp(iseq, 5),
};
self.jump_pc(9, disp);
}
Inst::SEND => {
let receiver = self.stack_pop();
try_err!(self, self.vm_send(iseq, receiver));
self.pc += 17;
}
Inst::SEND_SELF => {
let receiver = context.self_value;
try_err!(self, self.vm_send(iseq, receiver));
self.pc += 17;
}
Inst::YIELD => {
try_err!(self, self.eval_yield(iseq));
self.pc += 5;
}
Inst::DEF_CLASS => {
let is_module = self.read8(iseq, 1) == 1;
let id = self.read_id(iseq, 2);
let method = self.read_methodref(iseq, 6);
let super_val = self.stack_pop();
let val = match self.globals.builtins.object.get_var(id) {
Some(val) => {
if val.is_module().is_some() != is_module {
return Err(self.error_type(format!(
"{} is not {}.",
self.globals.get_ident_name(id),
if is_module { "module" } else { "class" },
)));
};
let classref = self.expect_module(val.clone())?;
if !super_val.is_nil() && classref.superclass.id() != super_val.id() {
return Err(self.error_type(format!(
"superclass mismatch for class {}.",
self.globals.get_ident_name(id),
)));
};
val.clone()
}
None => {
let super_val = if super_val.is_nil() {
self.globals.builtins.object
} else {
self.expect_class(super_val, "Superclass")?;
super_val
};
let classref = ClassRef::from(id, super_val);
let val = if is_module {
Value::module(&mut self.globals, classref)
} else {
Value::class(&mut self.globals, classref)
};
self.class().set_var(id, val);
val
}
};
self.class_push(val);
let mut iseq = self.get_iseq(method)?;
iseq.class_defined = self.gen_class_defined(val);
let arg = Args::new0();
try_err!(self, self.eval_send(method, val, &arg));
self.pc += 10;
self.class_pop();
}
Inst::DEF_METHOD => {
let id = self.read_id(iseq, 1);
let method = self.read_methodref(iseq, 5);
let mut iseq = self.get_iseq(method)?;
iseq.class_defined = self.gen_class_defined(None);
self.define_method(id, method);
if self.define_mode().module_function {
self.define_singleton_method(self.class(), id, method)?;
};
self.pc += 9;
}
Inst::DEF_SMETHOD => {
let id = self.read_id(iseq, 1);
let method = self.read_methodref(iseq, 5);
let mut iseq = self.get_iseq(method)?;
iseq.class_defined = self.gen_class_defined(None);
let singleton = self.stack_pop();
self.define_singleton_method(singleton, id, method)?;
if self.define_mode().module_function {
self.define_method(id, method);
};
self.pc += 9;
}
Inst::TO_S => {
let val = self.stack_pop();
let s = self.val_to_s(val);
let res = Value::string(&self.globals, s);
self.stack_push(res);
self.pc += 1;
}
Inst::POP => {
self.stack_pop();
self.pc += 1;
}
Inst::DUP => {
let len = self.read_usize(iseq, 1);
let stack_len = self.exec_stack.len();
for i in stack_len - len..stack_len {
let val = self.exec_stack[i];
self.stack_push(val);
}
self.pc += 5;
}
Inst::TAKE => {
let len = self.read_usize(iseq, 1);
let val = self.stack_pop();
match val.as_array() {
Some(info) => {
let elem = &info.elements;
let ary_len = elem.len();
if len <= ary_len {
for i in 0..len {
self.stack_push(elem[i]);
}
} else {
for i in 0..ary_len {
self.stack_push(elem[i]);
}
for _ in ary_len..len {
self.stack_push(Value::nil());
}
}
}
None => {
self.stack_push(val);
for _ in 0..len - 1 {
self.stack_push(Value::nil());
}
}
}
self.pc += 5;
}
_ => return Err(self.error_unimplemented("Unimplemented instruction.")),
}
}
}
}
impl VM {
pub fn error_nomethod(&self, msg: impl Into<String>) -> RubyError {
let loc = self.get_loc();
RubyError::new_runtime_err(
RuntimeErrKind::NoMethod(msg.into()),
self.source_info(),
loc,
)
}
pub fn error_undefined_op(
&self,
method_name: impl Into<String>,
rhs: Value,
lhs: Value,
) -> RubyError {
self.error_nomethod(format!(
"undefined method `{}' {} for {}",
method_name.into(),
self.globals.get_class_name(rhs),
self.globals.get_class_name(lhs)
))
}
pub fn error_undefined_method(
&self,
method_name: impl Into<String>,
receiver: Value,
) -> RubyError {
self.error_nomethod(format!(
"undefined method `{}' for {}",
method_name.into(),
self.globals.get_class_name(receiver)
))
}
pub fn error_unimplemented(&self, msg: impl Into<String>) -> RubyError {
let loc = self.get_loc();
RubyError::new_runtime_err(
RuntimeErrKind::Unimplemented(msg.into()),
self.source_info(),
loc,
)
}
pub fn error_internal(&self, msg: impl Into<String>) -> RubyError {
let loc = self.get_loc();
RubyError::new_runtime_err(
RuntimeErrKind::Internal(msg.into()),
self.source_info(),
loc,
)
}
pub fn error_name(&self, msg: impl Into<String>) -> RubyError {
let loc = self.get_loc();
RubyError::new_runtime_err(RuntimeErrKind::Name(msg.into()), self.source_info(), loc)
}
pub fn error_type(&self, msg: impl Into<String>) -> RubyError {
let loc = self.get_loc();
RubyError::new_runtime_err(RuntimeErrKind::Type(msg.into()), self.source_info(), loc)
}
pub fn error_argument(&self, msg: impl Into<String>) -> RubyError {
let loc = self.get_loc();
RubyError::new_runtime_err(
RuntimeErrKind::Argument(msg.into()),
self.source_info(),
loc,
)
}
pub fn error_regexp(&self, err: fancy_regex::Error) -> RubyError {
let loc = self.get_loc();
RubyError::new_runtime_err(
RuntimeErrKind::Regexp(format!(
"Invalid string for a regular expression. {:?}",
err
)),
self.source_info(),
loc,
)
}
pub fn error_index(&self, msg: impl Into<String>) -> RubyError {
let loc = self.get_loc();
RubyError::new_runtime_err(RuntimeErrKind::Index(msg.into()), self.source_info(), loc)
}
pub fn error_fiber(&self, msg: impl Into<String>) -> RubyError {
let loc = self.get_loc();
RubyError::new_runtime_err(RuntimeErrKind::Fiber(msg.into()), self.source_info(), loc)
}
pub fn error_method_return(&self, method: MethodRef) -> RubyError {
let loc = self.get_loc();
RubyError::new_method_return(method, self.source_info(), loc)
}
pub fn error_block_return(&self) -> RubyError {
let loc = self.get_loc();
RubyError::new_block_return(self.source_info(), loc)
}
pub fn check_args_num(&self, len: usize, num: usize) -> Result<(), RubyError> {
if len == num {
Ok(())
} else {
Err(self.error_argument(format!(
"Wrong number of arguments. (given {}, expected {})",
len, num
)))
}
}
pub fn check_args_range(&self, len: usize, min: usize, max: usize) -> Result<(), RubyError> {
if min <= len && len <= max {
Ok(())
} else {
Err(self.error_argument(format!(
"Wrong number of arguments. (given {}, expected {}..{})",
len, min, max
)))
}
}
pub fn check_args_min(&self, len: usize, min: usize) -> Result<(), RubyError> {
if min <= len {
Ok(())
} else {
Err(self.error_argument(format!(
"Wrong number of arguments. (given {}, expected {}+)",
len, min
)))
}
}
}
impl VM {
pub fn expect_block(&self, block: Option<MethodRef>) -> Result<MethodRef, RubyError> {
match block {
Some(method) => Ok(method),
None => return Err(self.error_argument("Currently, needs block.")),
}
}
pub fn expect_integer(&mut self, val: Value, msg: &str) -> Result<i64, RubyError> {
val.as_fixnum().ok_or_else(|| {
let inspect = self.val_inspect(val);
self.error_type(format!("{} must be Integer. (given:{})", msg, inspect))
})
}
pub fn expect_flonum(&mut self, val: Value, msg: &str) -> Result<f64, RubyError> {
val.as_flonum().ok_or_else(|| {
let inspect = self.val_inspect(val);
self.error_type(format!("{} must be Float. (given:{})", msg, inspect))
})
}
pub fn expect_string<'a>(
&mut self,
val: &'a Value,
msg: &str,
) -> Result<&'a String, RubyError> {
let rstring = val.as_rstring().ok_or_else(|| {
let inspect = self.val_inspect(val.clone());
self.error_type(format!("{} must be String. (given:{})", msg, inspect))
})?;
rstring.as_string(self)
}
pub fn expect_array(&mut self, val: Value, msg: &str) -> Result<ArrayRef, RubyError> {
val.as_array().ok_or_else(|| {
let inspect = self.val_inspect(val);
self.error_type(format!("{} must be Array. (given:{})", msg, inspect))
})
}
pub fn expect_hash(&mut self, val: Value, msg: &str) -> Result<HashRef, RubyError> {
val.as_hash().ok_or_else(|| {
let inspect = self.val_inspect(val);
self.error_type(format!("{} must be Hash. (given:{})", msg, inspect))
})
}
/// Returns `ClassRef` if `self` is a Class.
/// When `self` is not a Class, returns `TypeError`.
pub fn expect_class(&mut self, val: Value, msg: &str) -> Result<ClassRef, RubyError> {
val.is_class().ok_or_else(|| {
let val = self.val_inspect(val);
self.error_type(format!("{} must be Class. (given:{})", msg, val))
})
}
pub fn expect_module(&mut self, val: Value) -> Result<ClassRef, RubyError> {
val.as_module().ok_or_else(|| {
let val = self.val_inspect(val);
self.error_type(format!("Must be Module or Class. (given:{})", val))
})
}
pub fn expect_object(&self, val: Value, error_msg: &str) -> Result<ObjectRef, RubyError> {
match val.is_object() {
Some(oref) => Ok(oref),
None => Err(self.error_argument(error_msg)),
}
}
pub fn expect_fiber(&self, val: Value, error_msg: &str) -> Result<FiberRef, RubyError> {
match val.is_object() {
Some(oref) => match oref.kind {
ObjKind::Fiber(f) => Ok(f),
_ => Err(self.error_argument(error_msg)),
},
None => Err(self.error_argument(error_msg)),
}
}
pub fn expect_enumerator(&self, val: Value, error_msg: &str) -> Result<EnumRef, RubyError> {
match val.is_object() {
Some(oref) => match oref.kind {
ObjKind::Enumerator(e) => Ok(e),
_ => Err(self.error_argument(error_msg)),
},
None => Err(self.error_argument(error_msg)),
}
}
}
impl VM {
fn get_loc(&self) -> Loc {
let sourcemap = &self.context().iseq_ref.iseq_sourcemap;
sourcemap
.iter()
.find(|x| x.0 == ISeqPos::from(self.pc))
.unwrap_or(&(ISeqPos::from(0), Loc(0, 0)))
.1
}
fn get_nearest_class_stack(&self) -> Option<ClassListRef> {
let mut class_stack = None;
for context in self.exec_context.iter().rev() {
match context.iseq_ref.class_defined {
Some(class_list) => {
class_stack = Some(class_list);
break;
}
None => {}
}
}
class_stack
}
/// Return None in top-level.
fn gen_class_defined(&self, new_class: impl Into<Option<Value>>) -> Option<ClassListRef> {
let new_class = new_class.into();
match new_class {
Some(class) => {
let outer = self.get_nearest_class_stack();
let class_list = ClassList::new(outer, class);
Some(ClassListRef::new(class_list))
}
None => self.get_nearest_class_stack(),
}
}
// Search class stack for the constant.
fn get_env_const(&self, id: IdentId) -> Option<Value> {
let mut class_list = match self.get_nearest_class_stack() {
Some(list) => list,
None => return None,
};
loop {
match class_list.class.get_var(id) {
Some(val) => return Some(val),
None => {}
}
class_list = match class_list.outer {
Some(class) => class,
None => return None,
};
}
}
/// Search class inheritance chain for the constant.
pub fn get_super_const(&self, mut class: Value, id: IdentId) -> VMResult {
loop {
match class.get_var(id) {
Some(val) => {
return Ok(val);
}
None => match class.superclass() {
Some(superclass) => {
class = superclass;
}
None => {
let name = self.globals.get_ident_name(id);
return Err(self.error_name(format!("Uninitialized constant {}.", name)));
}
},
}
}
}
pub fn get_global_var(&self, id: IdentId) -> Value {
match self.globals.global_var.get(&id) {
Some(val) => val.clone(),
None => Value::nil(),
}
}
pub fn set_global_var(&mut self, id: IdentId, val: Value) {
self.globals.global_var.insert(id, val);
}
}
// Utilities for method call
impl VM {
/// Get a method from the method cache if saved in it.
/// Otherwise, search a class chain for the method.
fn get_method_from_cache(
&mut self,
cache_slot: u32,
receiver: Value,
method_id: IdentId,
) -> Result<MethodRef, RubyError> {
let rec_class = receiver.get_class_object_for_method(&self.globals);
if rec_class.is_nil() {
return Err(self.error_unimplemented("receiver's class is nil."));
};
match self
.globals
.get_method_from_inline_cache(cache_slot, rec_class)
{
Some(method) => Ok(method),
_ => {
let method = self.get_instance_method(rec_class, method_id)?;
self.globals
.set_inline_cache_entry(cache_slot, rec_class, method);
Ok(method)
}
}
}
fn fallback_to_method(&mut self, method: IdentId, lhs: Value, rhs: Value) -> VMResult {
match self.get_method(lhs, method) {
Ok(mref) => {
let arg = Args::new1(rhs);
let val = self.eval_send(mref, lhs, &arg)?;
Ok(val)
}
Err(_) => {
let name = self.globals.get_ident_name(method);
Err(self.error_undefined_op(name, rhs, lhs))
}
}
}
fn fallback_to_method_with_cache(
&mut self,
lhs: Value,
rhs: Value,
method: IdentId,
cache: u32,
) -> VMResult {
let methodref = self.get_method_from_cache(cache, lhs, method)?;
let arg = Args::new1(rhs);
self.eval_send(methodref, lhs, &arg)
}
}
macro_rules! eval_op {
($vm:ident, $iseq:ident, $rhs:expr, $lhs:expr, $op:ident, $id:expr) => {
let val = match ($lhs.unpack(), $rhs.unpack()) {
(RV::Integer(lhs), RV::Integer(rhs)) => Value::fixnum(lhs.$op(rhs)),
(RV::Integer(lhs), RV::Float(rhs)) => Value::flonum((lhs as f64).$op(rhs)),
(RV::Float(lhs), RV::Integer(rhs)) => Value::flonum(lhs.$op(rhs as f64)),
(RV::Float(lhs), RV::Float(rhs)) => Value::flonum(lhs.$op(rhs)),
_ => {
let cache = $vm.read32($iseq, 1);
return $vm.fallback_to_method_with_cache($lhs, $rhs, $id, cache);
}
};
return Ok(val);
};
}
impl VM {
fn eval_add(&mut self, rhs: Value, lhs: Value, iseq: &ISeq) -> VMResult {
use std::ops::Add;
eval_op!(self, iseq, rhs, lhs, add, IdentId::_ADD);
}
fn eval_sub(&mut self, rhs: Value, lhs: Value, iseq: &ISeq) -> VMResult {
use std::ops::Sub;
eval_op!(self, iseq, rhs, lhs, sub, IdentId::_SUB);
}
fn eval_mul(&mut self, rhs: Value, lhs: Value, iseq: &ISeq) -> VMResult {
use std::ops::Mul;
eval_op!(self, iseq, rhs, lhs, mul, IdentId::_MUL);
}
fn eval_addi(&mut self, lhs: Value, i: i32) -> VMResult {
use std::ops::Add;
let val = match lhs.unpack() {
RV::Integer(lhs) => Value::fixnum(lhs.add(i as i64)),
RV::Float(lhs) => Value::flonum(lhs.add(i as f64)),
_ => return self.fallback_to_method(IdentId::_ADD, lhs, Value::fixnum(i as i64)),
};
Ok(val)
}
fn eval_subi(&mut self, lhs: Value, i: i32) -> VMResult {
let val = match lhs.unpack() {
RV::Integer(lhs) => Value::fixnum(lhs - i as i64),
RV::Float(lhs) => Value::flonum(lhs - i as f64),
_ => return self.fallback_to_method(IdentId::_SUB, lhs, Value::fixnum(i as i64)),
};
Ok(val)
}
fn eval_div(&mut self, rhs: Value, lhs: Value) -> VMResult {
use std::ops::Div;
match (lhs.unpack(), rhs.unpack()) {
(RV::Integer(lhs), RV::Integer(rhs)) => Ok(Value::fixnum(lhs.div(rhs))),
(RV::Integer(lhs), RV::Float(rhs)) => Ok(Value::flonum((lhs as f64).div(rhs))),
(RV::Float(lhs), RV::Integer(rhs)) => Ok(Value::flonum(lhs.div(rhs as f64))),
(RV::Float(lhs), RV::Float(rhs)) => Ok(Value::flonum(lhs.div(rhs))),
(_, _) => return Err(self.error_undefined_op("/", rhs, lhs)),
}
}
fn eval_rem(&mut self, rhs: Value, lhs: Value) -> VMResult {
fn rem_floorf64(self_: f64, other: f64) -> f64 {
if self_ > 0.0 && other < 0.0 {
((self_ - 1.0) % other) + other + 1.0
} else if self_ < 0.0 && other > 0.0 {
((self_ + 1.0) % other) + other - 1.0
} else {
self_ % other
}
}
use divrem::*;
let val = match (lhs.unpack(), rhs.unpack()) {
(RV::Integer(lhs), RV::Integer(rhs)) => Value::fixnum(lhs.rem_floor(rhs)),
(RV::Integer(lhs), RV::Float(rhs)) => Value::flonum(rem_floorf64(lhs as f64, rhs)),
(RV::Float(lhs), RV::Integer(rhs)) => Value::flonum(rem_floorf64(lhs, rhs as f64)),
(RV::Float(lhs), RV::Float(rhs)) => Value::flonum(rem_floorf64(lhs, rhs)),
(_, _) => return self.fallback_to_method(IdentId::_REM, lhs, rhs),
};
Ok(val)
}
fn eval_exp(&mut self, rhs: Value, lhs: Value) -> VMResult {
let val = match (lhs.unpack(), rhs.unpack()) {
(RV::Integer(lhs), RV::Integer(rhs)) => {
if 0 <= rhs && rhs <= std::u32::MAX as i64 {
Value::fixnum(lhs.pow(rhs as u32))
} else {
Value::flonum((lhs as f64).powf(rhs as f64))
}
}
(RV::Integer(lhs), RV::Float(rhs)) => Value::flonum((lhs as f64).powf(rhs)),
(RV::Float(lhs), RV::Integer(rhs)) => Value::flonum(lhs.powf(rhs as f64)),
(RV::Float(lhs), RV::Float(rhs)) => Value::flonum(lhs.powf(rhs)),
_ => {
return self.fallback_to_method(IdentId::_POW, lhs, rhs);
}
};
Ok(val)
}
fn eval_shl(&mut self, rhs: Value, lhs: Value, iseq: &ISeq) -> VMResult {
match lhs.unpack() {
RV::Integer(lhs) => {
match rhs.as_fixnum() {
Some(rhs) => return Ok(Value::fixnum(lhs << rhs)),
_ => {}
};
}
RV::Object(lhs_o) => match lhs_o.kind {
ObjKind::Array(mut aref) => {
aref.elements.push(rhs);
return Ok(lhs);
}
_ => {}
},
_ => {}
};
let cache = self.read32(iseq, 1);
let val = self.fallback_to_method_with_cache(lhs, rhs, IdentId::_SHL, cache)?;
Ok(val)
}
fn eval_shr(&mut self, rhs: Value, lhs: Value) -> VMResult {
match (lhs.unpack(), rhs.unpack()) {
(RV::Integer(lhs), RV::Integer(rhs)) => Ok(Value::fixnum(lhs >> rhs)),
(_, _) => return Err(self.error_undefined_op(">>", rhs, lhs)),
}
}
fn eval_bitand(&mut self, rhs: Value, lhs: Value) -> VMResult {
match (lhs.unpack(), rhs.unpack()) {
(RV::Integer(lhs), RV::Integer(rhs)) => Ok(Value::fixnum(lhs & rhs)),
(_, _) => return Err(self.error_undefined_op("&", rhs, lhs)),
}
}
fn eval_bitor(&mut self, rhs: Value, lhs: Value) -> VMResult {
match (lhs.unpack(), rhs.unpack()) {
(RV::Integer(lhs), RV::Integer(rhs)) => Ok(Value::fixnum(lhs | rhs)),
(_, _) => return Err(self.error_undefined_op("|", rhs, lhs)),
}
}
fn eval_bitxor(&mut self, rhs: Value, lhs: Value) -> VMResult {
match (lhs.unpack(), rhs.unpack()) {
(RV::Integer(lhs), RV::Integer(rhs)) => Ok(Value::fixnum(lhs ^ rhs)),
(_, _) => return Err(self.error_undefined_op("^", rhs, lhs)),
}
}
fn eval_bitnot(&mut self, lhs: Value) -> VMResult {
match lhs.unpack() {
RV::Integer(lhs) => Ok(Value::fixnum(!lhs)),
_ => Err(self.error_nomethod("NoMethodError: '~'")),
}
}
}
macro_rules! eval_cmp {
($vm:ident, $rhs:expr, $lhs:expr, $op:ident, $id:expr) => {
match ($lhs.unpack(), $rhs.unpack()) {
(RV::Integer(lhs), RV::Integer(rhs)) => Ok(Value::bool(lhs.$op(&rhs))),
(RV::Float(lhs), RV::Integer(rhs)) => Ok(Value::bool(lhs.$op(&(rhs as f64)))),
(RV::Integer(lhs), RV::Float(rhs)) => Ok(Value::bool((lhs as f64).$op(&rhs))),
(RV::Float(lhs), RV::Float(rhs)) => Ok(Value::bool(lhs.$op(&rhs))),
(_, _) => return $vm.fallback_to_method($id, $lhs, $rhs),
}
};
}
impl VM {
pub fn eval_eq(&self, rhs: Value, lhs: Value) -> Result<bool, RubyError> {
Ok(rhs.equal(lhs))
}
pub fn eval_teq(&mut self, rhs: Value, lhs: Value) -> Result<bool, RubyError> {
match lhs.is_object() {
Some(oref) => match oref.kind {
ObjKind::Class(_) => {
let res = rhs.get_class_object(&self.globals).id() == lhs.id();
Ok(res)
}
ObjKind::Regexp(re) => {
let given = match rhs.unpack() {
RV::Symbol(sym) => self.globals.get_ident_name(sym),
RV::Object(_) => match rhs.as_string() {
Some(s) => s,
None => return Ok(false),
},
_ => return Ok(false),
}
.to_owned();
let res = Regexp::find_one(self, &re.regexp, &given)?.is_some();
Ok(res)
}
_ => Ok(self.eval_eq(lhs, rhs).unwrap_or(false)),
},
None => Ok(self.eval_eq(lhs, rhs).unwrap_or(false)),
}
}
fn eval_ge(&mut self, rhs: Value, lhs: Value) -> VMResult {
eval_cmp!(self, rhs, lhs, ge, IdentId::_GE)
}
pub fn eval_gt(&mut self, rhs: Value, lhs: Value) -> VMResult {
eval_cmp!(self, rhs, lhs, gt, IdentId::_GT)
}
pub fn eval_cmp(&mut self, rhs: Value, lhs: Value) -> VMResult {
let res = match lhs.unpack() {
RV::Integer(lhs) => match rhs.unpack() {
RV::Integer(rhs) => lhs.partial_cmp(&rhs),
RV::Float(rhs) => (lhs as f64).partial_cmp(&rhs),
_ => return Ok(Value::nil()),
},
RV::Float(lhs) => match rhs.unpack() {
RV::Integer(rhs) => lhs.partial_cmp(&(rhs as f64)),
RV::Float(rhs) => lhs.partial_cmp(&rhs),
_ => return Ok(Value::nil()),
},
_ => {
let id = self.globals.get_ident_id("<=>");
return self.fallback_to_method(id, lhs, rhs);
}
};
match res {
Some(ord) => Ok(Value::fixnum(ord as i64)),
None => Ok(Value::nil()),
}
}
pub fn sort_array(&mut self, mut aref: ArrayRef) -> Result<(), RubyError> {
if aref.elements.len() > 0 {
let val = aref.elements[0];
for i in 1..aref.elements.len() {
match self.eval_cmp(aref.elements[i], val)? {
v if v == Value::nil() => {
let lhs = self.globals.get_class_name(val);
let rhs = self.globals.get_class_name(aref.elements[i]);
return Err(self.error_argument(format!(
"Comparison of {} with {} failed.",
lhs, rhs
)));
}
_ => {}
}
}
aref.elements
.sort_by(|a, b| self.eval_cmp(*b, *a).unwrap().to_ordering());
}
Ok(())
}
}
impl VM {
fn create_regexp(&mut self, arg: Value) -> VMResult {
let mut arg = match arg.as_string() {
Some(arg) => arg.clone(),
None => return Err(self.error_argument("Illegal argument for CREATE_REGEXP")),
};
match arg.pop().unwrap() {
'i' => arg.insert_str(0, "(?mi)"),
'm' => arg.insert_str(0, "(?ms)"),
'x' => arg.insert_str(0, "(?mx)"),
'o' => arg.insert_str(0, "(?mo)"),
'-' => arg.insert_str(0, "(?m)"),
_ => return Err(self.error_internal("Illegal internal regexp expression.")),
};
self.create_regexp_from_string(&arg)
}
}
// API's for handling values.
impl VM {
pub fn val_to_bool(&self, val: Value) -> bool {
!val.is_nil() && !val.is_false_val() && !val.is_uninitialized()
}
pub fn val_to_s(&mut self, val: Value) -> String {
match val.unpack() {
RV::Uninitialized => "[Uninitialized]".to_string(),
RV::Nil => "".to_string(),
RV::Bool(b) => match b {
true => "true".to_string(),
false => "false".to_string(),
},
RV::Integer(i) => i.to_string(),
RV::Float(f) => {
if f.fract() == 0.0 {
format!("{:.1}", f)
} else {
f.to_string()
}
}
RV::Symbol(i) => format!("{}", self.globals.get_ident_name(i)),
RV::Object(oref) => match &oref.kind {
ObjKind::String(s) => s.to_s(),
ObjKind::Class(cref) => match cref.name {
Some(id) => format! {"{}", self.globals.get_ident_name(id)},
None => format! {"#<Class:0x{:x}>", cref.id()},
},
ObjKind::Ordinary => oref.to_s(&self.globals),
ObjKind::Array(aref) => aref.to_s(self),
ObjKind::Range(rinfo) => rinfo.to_s(self),
ObjKind::Regexp(rref) => format!("({})", rref.regexp.as_str().to_string()),
ObjKind::Hash(href) => href.to_s(self),
_ => format!("{:?}", oref.kind),
},
}
}
pub fn val_inspect(&mut self, val: Value) -> String {
match val.unpack() {
RV::Uninitialized => "[Uninitialized]".to_string(),
RV::Nil => "nil".to_string(),
RV::Bool(b) => match b {
true => "true".to_string(),
false => "false".to_string(),
},
RV::Integer(i) => i.to_string(),
RV::Float(f) => {
if f.fract() == 0.0 {
format!("{:.1}", f)
} else {
f.to_string()
}
}
RV::Symbol(sym) => format!(":{}", self.globals.get_ident_name(sym)),
RV::Object(oref) => match &oref.kind {
ObjKind::String(s) => s.inspect(),
ObjKind::Range(rinfo) => rinfo.inspect(self),
ObjKind::Class(cref) => match cref.name {
Some(id) => format! {"{}", self.globals.get_ident_name(id)},
None => format! {"#<Class:0x{:x}>", cref.id()},
},
ObjKind::Module(cref) => match cref.name {
Some(id) => format! {"{}", self.globals.get_ident_name(id)},
None => format! {"#<Module:0x{:x}>", cref.id()},
},
ObjKind::Array(aref) => aref.to_s(self),
ObjKind::Regexp(rref) => format!("/{}/", rref.regexp.as_str().to_string()),
ObjKind::Ordinary => oref.inspect(self),
ObjKind::Proc(pref) => format!("#<Proc:0x{:x}>", pref.id()),
ObjKind::Hash(href) => href.to_s(self),
_ => {
let id = self.globals.get_ident_id("inspect");
self.send0(val, id)
.unwrap()
.as_string()
.unwrap()
.to_string()
}
},
}
}
pub fn send0(&mut self, receiver: Value, method_id: IdentId) -> VMResult {
let method = self.get_method(receiver, method_id)?;
let args = Args::new0();
let val = self.eval_send(method, receiver, &args)?;
Ok(val)
}
}
impl VM {
fn vm_send(&mut self, iseq: &ISeq, receiver: Value) -> VMResult {
let method_id = self.read_id(iseq, 1);
let args_num = self.read16(iseq, 5);
let flag = self.read16(iseq, 7);
let cache_slot = self.read32(iseq, 9);
let block = self.read32(iseq, 13);
let methodref = self.get_method_from_cache(cache_slot, receiver, method_id)?;
let keyword = if flag & 0b01 == 1 {
let val = self.stack_pop();
Some(val)
} else {
None
};
let mut args = self.pop_args_to_ary(args_num as usize);
let block = if block != 0 {
Some(MethodRef::from(block))
} else if flag & 0b10 == 2 {
let val = self.stack_pop();
let method = val
.as_proc()
.ok_or_else(|| self.error_argument("Block argument must be Proc."))?
.context
.iseq_ref
.method;
Some(method)
} else {
None
};
args.block = block;
args.kw_arg = keyword;
let val = self.eval_send(methodref, receiver, &args)?;
Ok(val)
}
}
impl VM {
/// Evaluate method with given `self_val`, `args` and no outer context.
pub fn eval_send(&mut self, methodref: MethodRef, self_val: Value, args: &Args) -> VMResult {
self.eval_method(methodref, self_val, None, args)
}
/// Evaluate method with self_val of current context, current context as outer context, and given `args`.
pub fn eval_block(&mut self, methodref: MethodRef, args: &Args) -> VMResult {
let context = self.context();
self.eval_method(methodref, context.self_value, Some(context), args)
}
/// Evaluate method with self_val of current context, caller context as outer context, and given `args`.
fn eval_yield(&mut self, iseq: &ISeq) -> VMResult {
let args_num = self.read32(iseq, 1) as usize;
let args = self.pop_args_to_ary(args_num);
let mut context = self.context();
loop {
if let ISeqKind::Method(_) = context.kind {
break;
}
context = context
.outer
.ok_or_else(|| self.error_unimplemented("No block given."))?;
}
let method = context
.block
.ok_or_else(|| self.error_unimplemented("No block given."))?;
let res = self.eval_method(
method,
self.context().self_value,
Some(self.caller_context()),
&args,
)?;
Ok(res)
}
/// Evaluate method with given `self_val`, `outer` context, and `args`.
pub fn eval_method(
&mut self,
methodref: MethodRef,
self_val: Value,
outer: Option<ContextRef>,
args: &Args,
) -> VMResult {
if methodref.is_none() {
let res = match args.len() {
0 => Value::nil(),
1 => args[0],
_ => {
let ary = args.to_vec();
Value::array_from(&self.globals, ary)
}
};
return Ok(res);
};
let info = self.globals.get_method_info(methodref);
#[allow(unused_variables, unused_mut)]
let mut inst: u8;
#[cfg(feature = "perf")]
{
inst = self.perf.get_prev_inst();
}
let val = match info {
MethodInfo::BuiltinFunc { func, .. } => {
#[cfg(feature = "perf")]
{
self.perf.get_perf(Perf::EXTERN);
}
let val = func(self, self_val, args)?;
#[cfg(feature = "perf")]
{
self.perf.get_perf_no_count(inst);
}
val
}
MethodInfo::AttrReader { id } => match self_val.is_object() {
Some(oref) => match oref.get_var(*id) {
Some(v) => v,
None => Value::nil(),
},
None => unreachable!("AttrReader must be used only for class instance."),
},
MethodInfo::AttrWriter { id } => match self_val.is_object() {
Some(mut oref) => {
oref.set_var(*id, args[0]);
args[0]
}
None => unreachable!("AttrReader must be used only for class instance."),
},
MethodInfo::RubyFunc { iseq } => {
let iseq = *iseq;
let context = Context::from_args(self, self_val, iseq, args, outer)?;
let val = self.run_context(ContextRef::from_local(&context))?;
#[cfg(feature = "perf")]
{
self.perf.get_perf_no_count(inst);
}
val
}
};
Ok(val)
}
pub fn eval_enumerator(&mut self, eref: EnumRef) -> VMResult {
eref.eval(self)
}
}
// API's for handling instance/singleton methods.
impl VM {
pub fn define_method(&mut self, id: IdentId, method: MethodRef) {
if self.exec_context.len() == 1 {
// A method defined in "top level" is registered as an object method.
self.add_object_method(id, method);
} else {
// A method defined in a class definition is registered as an instance method of the class.
self.add_instance_method(self.class(), id, method);
}
}
pub fn define_singleton_method(
&mut self,
obj: Value,
id: IdentId,
method: MethodRef,
) -> Result<(), RubyError> {
if self.exec_context.len() == 1 {
// A method defined in "top level" is registered as an object method.
self.add_object_method(id, method);
Ok(())
} else {
// A method defined in a class definition is registered as an instance method of the class.
self.add_singleton_method(obj, id, method)
}
}
pub fn add_singleton_method(
&mut self,
obj: Value,
id: IdentId,
info: MethodRef,
) -> Result<(), RubyError> {
self.globals.class_version += 1;
let singleton = self.get_singleton_class(obj)?;
let mut singleton_class = singleton.as_class();
singleton_class.method_table.insert(id, info);
Ok(())
}
pub fn add_instance_method(
&mut self,
class_obj: Value,
id: IdentId,
info: MethodRef,
) -> Option<MethodRef> {
self.globals.class_version += 1;
class_obj.as_module().unwrap().method_table.insert(id, info)
}
pub fn add_object_method(&mut self, id: IdentId, info: MethodRef) {
self.add_instance_method(self.globals.builtins.object, id, info);
}
/// Get method(MethodRef) for receiver.
pub fn get_method(
&mut self,
receiver: Value,
method_id: IdentId,
) -> Result<MethodRef, RubyError> {
let rec_class = receiver.get_class_object_for_method(&self.globals);
let method = self.get_instance_method(rec_class, method_id)?;
Ok(method)
}
/// Get instance method(MethodRef) for the class object.
pub fn get_instance_method(
&mut self,
mut class: Value,
method: IdentId,
) -> Result<MethodRef, RubyError> {
match self.globals.get_method_cache_entry(class, method) {
Some(MethodCacheEntry { version, method }) => {
if *version == self.globals.class_version {
return Ok(*method);
}
}
None => {}
};
let original_class = class;
let mut singleton_flag = original_class.as_class().is_singleton;
loop {
match class.get_instance_method(method) {
Some(methodref) => {
self.globals
.add_method_cache_entry(original_class, method, methodref);
return Ok(methodref);
}
None => match class.superclass() {
Some(superclass) => class = superclass,
None => {
if singleton_flag {
singleton_flag = false;
class = original_class.as_object().class();
} else {
let inspect = self.val_inspect(original_class);
let method_name = self.globals.get_ident_name(method);
return Err(self.error_nomethod(format!(
"no method `{}' found for {}",
method_name, inspect
)));
}
}
},
};
}
}
pub fn get_singleton_class(&mut self, obj: Value) -> VMResult {
self.globals
.get_singleton_class(obj)
.map_err(|_| self.error_type("Can not define singleton."))
}
}
impl VM {
fn unwind_context(&mut self, err: &mut RubyError) {
self.context_pop().unwrap();
if let Some(context) = self.exec_context.last_mut() {
self.pc = context.pc;
err.info.push((self.source_info(), self.get_loc()));
};
}
pub fn fiber_send_to_parent(&mut self, val: VMResult) {
match &mut self.channel {
Some((tx, rx)) => {
tx.send(val.clone()).unwrap();
rx.recv().unwrap();
}
None => return,
};
#[cfg(feature = "trace")]
{
match val {
Ok(val) => println!("<=== yield Ok({})", self.val_inspect(val),),
Err(err) => println!("<=== yield Err({:?})", err.kind),
}
}
}
/// Get local variable table.
fn get_outer_context(&mut self, outer: u32) -> ContextRef {
let mut context = self.context();
for _ in 0..outer {
context = context.outer.unwrap();
}
context
}
/// Calculate array index.
pub fn get_array_index(&self, index: i64, len: usize) -> Result<usize, RubyError> {
if index < 0 {
let i = len as i64 + index;
if i < 0 {
return Err(self.error_unimplemented("Index out of range."));
};
Ok(i as usize)
} else {
Ok(index as usize)
}
}
fn pop_key_value_pair(&mut self, arg_num: usize) -> HashMap<HashKey, Value> {
let mut hash = HashMap::new();
for _ in 0..arg_num {
let value = self.stack_pop();
let key = self.stack_pop();
hash.insert(HashKey(key), value);
}
hash
}
fn pop_args_to_ary(&mut self, arg_num: usize) -> Args {
let mut args = Args::new(0);
for _ in 0..arg_num {
let val = self.stack_pop();
match val.as_splat() {
Some(inner) => match inner.as_rvalue() {
None => args.push(inner),
Some(obj) => match &obj.kind {
ObjKind::Array(aref) => {
for elem in &aref.elements {
args.push(*elem);
}
}
ObjKind::Range(rref) => {
let start = if rref.start.is_packed_fixnum() {
rref.start.as_packed_fixnum()
} else {
unimplemented!("Range start not fixnum.")
};
let end = if rref.end.is_packed_fixnum() {
rref.end.as_packed_fixnum()
} else {
unimplemented!("Range end not fixnum.")
} + if rref.exclude { 0 } else { 1 };
for i in start..end {
args.push(Value::fixnum(i));
}
}
_ => args.push(inner),
},
},
None => args.push(val),
};
}
args
}
/// Create new Proc object from `method`,
/// moving outer `Context`s on stack to heap.
pub fn create_proc(&mut self, method: MethodRef) -> VMResult {
self.move_outer_to_heap();
let context = self.create_block_context(method)?;
Ok(Value::procobj(&self.globals, context))
}
/// Move outer execution contexts on the stack to the heap.
fn move_outer_to_heap(&mut self) {
let mut prev_ctx: Option<ContextRef> = None;
for context in self.exec_context.iter_mut().rev() {
if !context.on_stack {
break;
};
let mut heap_context = context.dup();
heap_context.on_stack = false;
*context = heap_context;
if let Some(mut ctx) = prev_ctx {
ctx.outer = Some(heap_context);
};
if heap_context.outer.is_none() {
break;
}
prev_ctx = Some(heap_context);
}
}
/// Create a new execution context for a block.
pub fn create_block_context(&mut self, method: MethodRef) -> Result<ContextRef, RubyError> {
self.move_outer_to_heap();
let iseq = self.get_iseq(method)?;
let outer = self.context();
Ok(ContextRef::from(outer.self_value, None, iseq, Some(outer)))
}
pub fn get_iseq(&self, method: MethodRef) -> Result<ISeqRef, RubyError> {
self.globals.get_method_info(method).as_iseq(&self)
}
/// Create new Regexp object from `string`.
/// Regular expression meta characters are handled as is.
/// Returns RubyError if `string` was invalid regular expression.
pub fn create_regexp_from_string(&self, string: &str) -> VMResult {
let re = RegexpRef::from_string(string).map_err(|err| self.error_regexp(err))?;
let regexp = Value::regexp(&self.globals, re);
Ok(regexp)
}
/// Create fancy_regex::Regex from `string`.
/// Escapes all regular expression meta characters in `string`.
/// Returns RubyError if `string` was invalid regular expression.
pub fn regexp_from_string(&self, string: &str) -> Result<Regexp, RubyError> {
match fancy_regex::Regex::new(®ex::escape(string)) {
Ok(re) => Ok(Regexp::new(re)),
Err(err) => Err(self.error_regexp(err)),
}
}
}
|
use gssapi_sys;
use std::ptr;
use super::buffer::Buffer;
use super::credentials::Credentials;
use super::error::{Error, Result};
use super::name::Name;
use super::oid::OID;
#[derive(Debug)]
pub struct Context {
context_handle: gssapi_sys::gss_ctx_id_t,
mech_type: OID,
time_rec: u32,
flags: u32,
}
impl Context {
pub fn initiate<T: Into<Name>>(target_name: T) -> InitiateContextBuilder {
InitiateContextBuilder::new(target_name)
}
pub fn accept(credentials: Credentials) -> AcceptContextBuilder {
AcceptContextBuilder::new(credentials)
}
pub fn mech_type(&self) -> &OID {
&self.mech_type
}
pub fn time_rec(&self) -> u32 {
self.time_rec
}
pub fn flags(&self) -> u32 {
self.flags
}
}
impl Drop for Context {
fn drop(&mut self) {
let mut minor_status = 0;
let major_status = unsafe {
gssapi_sys::gss_delete_sec_context(
&mut minor_status,
&mut self.context_handle,
ptr::null_mut())
};
if major_status != gssapi_sys::GSS_S_COMPLETE {
panic!("failed to drop context {} {}", major_status, minor_status)
}
}
}
#[derive(Debug)]
pub struct InitiateContextBuilder {
state: InitiateContextState,
}
impl InitiateContextBuilder {
pub fn new<T: Into<Name>>(target_name: T) -> Self {
InitiateContextBuilder {
state: InitiateContextState::new(target_name),
}
}
pub fn mech_type(mut self, mech_type: OID) -> Self {
self.state.mech_type = mech_type;
self
}
pub fn flags(mut self, flags: u32) -> Self {
self.state.flags |= flags;
self
}
pub fn step(self) -> Result<(InitiateContextState, Buffer)> {
match try!(self.state.step(Buffer::new())) {
InitiateContext::Continue { initializer, token } => {
Ok((initializer, token))
},
InitiateContext::Done { .. } => {
unreachable!("succeeded at connecting without talking to server?")
}
}
}
}
#[derive(Debug)]
pub enum InitiateContext {
Continue {
initializer: InitiateContextState,
token: Buffer,
},
Done {
context: Context,
},
}
#[derive(Debug)]
pub struct InitiateContextState {
target_name: Name,
mech_type: OID,
flags: u32,
context_handle: gssapi_sys::gss_ctx_id_t,
}
impl InitiateContextState {
fn new<T: Into<Name>>(target_name: T) -> Self {
let target_name = target_name.into();
InitiateContextState {
target_name: target_name,
mech_type: OID::empty(),
flags: 0,
context_handle: ptr::null_mut(),
}
}
pub fn step(mut self, mut input_token: Buffer) -> Result<InitiateContext> {
let mut minor_status = 0;
let claimant_cred_handle = ptr::null_mut(); // no credentials
let time_req = 0;
let input_chan_bindings = ptr::null_mut(); // no channel bindings
let mut actual_mech_type = ptr::null_mut(); // ignore mech type
let mut output_token = Buffer::new();
let mut ret_flags = 0;
let mut time_rec = 0;
let major_status = unsafe {
gssapi_sys::gss_init_sec_context(
&mut minor_status,
claimant_cred_handle,
&mut self.context_handle,
self.target_name.get_handle(),
self.mech_type.get_handle(),
self.flags,
time_req,
input_chan_bindings,
input_token.get_handle(),
&mut actual_mech_type,
output_token.get_handle(),
&mut ret_flags,
&mut time_rec,
)
};
if self.context_handle.is_null() {
panic!("cannot create context");
}
let actual_mech_type = unsafe { OID::new(actual_mech_type) };
if major_status == gssapi_sys::GSS_S_COMPLETE {
Ok(InitiateContext::Done {
context: Context {
context_handle: self.context_handle,
mech_type: actual_mech_type,
time_rec: time_rec,
flags: ret_flags,
},
})
} else if major_status == gssapi_sys::GSS_S_CONTINUE_NEEDED {
Ok(InitiateContext::Continue {
initializer: self,
token: output_token,
})
} else {
Err(Error::new(major_status, minor_status, actual_mech_type))
}
}
pub fn final_step(self, input_token: Buffer) -> Result<Context> {
match try!(self.step(input_token)) {
InitiateContext::Done { context } => Ok(context),
InitiateContext::Continue { .. } => {
panic!("Server is done but client didn't finish?")
}
}
}
}
#[derive(Debug)]
pub struct AcceptContextBuilder {
state: AcceptContextState,
}
impl AcceptContextBuilder {
pub fn new(credentials: Credentials) -> Self {
AcceptContextBuilder {
state: AcceptContextState::new(credentials),
}
}
pub fn step(self, input_token: Buffer) -> Result<AcceptContext> {
self.state.step(input_token)
}
}
#[derive(Debug)]
pub enum AcceptContext {
Continue {
acceptor: AcceptContextState,
token: Buffer,
},
Done {
context: Context,
token: Buffer,
},
}
#[derive(Debug)]
pub struct AcceptContextState {
acceptor_credentials: Credentials,
context_handle: gssapi_sys::gss_ctx_id_t,
}
impl AcceptContextState {
fn new(credentials: Credentials) -> Self {
AcceptContextState {
acceptor_credentials: credentials,
context_handle: ptr::null_mut(),
}
}
pub fn step(mut self, mut input_token: Buffer) -> Result<AcceptContext> {
let mut minor_status = 0;
let input_chan_bindings = ptr::null_mut(); // no channel bindings
let mut src_name = ptr::null_mut();
let mut mech_type = ptr::null_mut(); // ignore mech type
let mut output_token = Buffer::new();
let mut ret_flags = 0;
let mut time_rec = 0;
let mut delegated_cred_handle = ptr::null_mut();
let major_status = unsafe {
gssapi_sys::gss_accept_sec_context(
&mut minor_status,
&mut self.context_handle,
self.acceptor_credentials.get_handle(),
input_token.get_handle(),
input_chan_bindings,
&mut src_name,
&mut mech_type,
output_token.get_handle(),
&mut ret_flags,
&mut time_rec,
&mut delegated_cred_handle,
)
};
if self.context_handle.is_null() {
panic!("cannot create context");
}
let mech_type = unsafe { OID::new(mech_type) };
if major_status == gssapi_sys::GSS_S_COMPLETE {
Ok(AcceptContext::Done {
context: Context {
context_handle: self.context_handle,
mech_type: mech_type,
time_rec: time_rec,
flags: ret_flags,
},
token: output_token,
})
} else if major_status == gssapi_sys::GSS_S_CONTINUE_NEEDED {
Ok(AcceptContext::Continue {
acceptor: self,
token: output_token,
})
} else {
Err(Error::new(major_status, minor_status, mech_type))
}
}
}
|
use super::{category::CategorySchema, comment::CommentSchema, embed::EmbedSchema};
use crate::{
graphql::{schema::Context, user::UserSchema},
models::{
comment::Comment,
embed::{Embed, Rating},
handler::Handler,
node::CategoryNode,
post::{Post, StatusPost},
user::User,
},
};
use chrono::prelude::*;
use diesel::prelude::*;
pub trait PostSchema {
fn id(&self) -> &i32;
fn author(&self, context: &Context) -> Option<Box<dyn UserSchema>>;
fn title(&self) -> &Option<String>;
fn createdAt(&self) -> &NaiveDateTime;
fn content(&self) -> &Option<String>;
fn status(&self) -> &Option<StatusPost>;
fn last_edited_at(&self) -> &Option<NaiveDateTime>;
fn last_edited_by(&self) -> &Option<String>;
fn embed(&self, context: &Context) -> Box<dyn EmbedSchema>;
fn rating(&self, context: &Context) -> Rating;
fn category(&self, context: &Context) -> Vec<Box<dyn CategorySchema>>;
fn comment(&self, context: &Context) -> Vec<Box<dyn CommentSchema>>;
}
impl PostSchema for Post {
fn id(&self) -> &i32 {
&self.id
}
fn author(&self, context: &Context) -> Option<Box<dyn UserSchema>> {
if let Some(user_id) = &self.author_id {
return match User::find_by_id(user_id, &context.conn) {
Ok(e) => Some(e),
Err(_) => None,
};
}
None
}
fn title(&self) -> &Option<String> {
&self.title
}
fn createdAt(&self) -> &NaiveDateTime {
&self.createdAt
}
fn content(&self) -> &Option<String> {
&self.content
}
fn status(&self) -> &Option<StatusPost> {
&self.status
}
fn last_edited_at(&self) -> &Option<NaiveDateTime> {
&self.last_edited_at
}
fn last_edited_by(&self) -> &Option<String> {
&self.last_edited_by
}
fn embed(&self, context: &Context) -> Box<dyn EmbedSchema> {
let conn: &MysqlConnection = &context.conn;
Embed::belonging_to(self)
.first::<Embed>(conn)
.map(Box::new)
.map(|embd| embd as Box<dyn EmbedSchema>)
.expect("failed to load embed")
}
fn rating(&self, context: &Context) -> Rating {
let conn: &MysqlConnection = &context.conn;
Rating::belonging_to(self).first::<Rating>(conn).expect("failed to load rating")
}
fn category(&self, context: &Context) -> Vec<Box<dyn CategorySchema>> {
let conn: &MysqlConnection = &context.conn;
CategoryNode::get_by_postId(&self, conn)
.into_iter()
.map(|e| e as Box<dyn CategorySchema>)
.collect()
}
fn comment(&self, context: &Context) -> Vec<Box<dyn CommentSchema + 'static>> {
let conn: &MysqlConnection = &context.conn;
Comment::belonging_to(self)
.load::<Comment>(conn)
.map(|e| {
e.into_iter()
.filter(|x| x.reply_for_id.is_none())
.map(Box::from)
.map(|e| e as Box<dyn CommentSchema>)
.collect()
})
.expect("failed load comment")
}
}
#[juniper::object(
name="Post",
Context=Context)]
impl Box<dyn PostSchema> {
fn id(&self) -> &i32 {
&self.id()
}
fn author(&self, context: &Context) -> Option<Box<dyn UserSchema>> {
self.author(context)
}
fn title(&self) -> &Option<String> {
&self.title()
}
fn createdAt(&self) -> &NaiveDateTime {
&self.createdAt()
}
fn content(&self) -> &Option<String> {
&self.content()
}
fn status(&self) -> &Option<StatusPost> {
&self.status()
}
fn last_edited_at(&self) -> &Option<NaiveDateTime> {
&self.last_edited_at()
}
fn last_edited_by(&self) -> &Option<String> {
&self.last_edited_by()
}
fn rating(&self, context: &Context) -> Rating {
self.rating(context)
}
fn embed(&self, context: &Context) -> Box<dyn EmbedSchema> {
self.embed(context)
}
fn category(&self, context: &Context) -> Vec<Box<dyn CategorySchema + 'static>> {
self.category(context)
}
fn comment(&self, context: &Context) -> Vec<Box<dyn CommentSchema + 'static>> {
self.comment(context)
}
}
|
//! A simple, thread-safe IRC server library.
#![unstable = "This has yet to be written."]
|
#![allow(unused_imports)]
use simplelog::Level::{Error, Info, Trace};
use tfdeploy::Tensor;
use errors::*;
use format::*;
use utils::*;
use {OutputParameters, Parameters};
/// Handles the `compare` subcommand.
#[cfg(not(feature = "tensorflow"))]
pub fn handle(_params: Parameters, _: OutputParameters) -> Result<()> {
bail!("Comparison requires the `tensorflow` feature.")
}
#[cfg(feature = "tensorflow")]
pub fn handle(params: Parameters, output_params: OutputParameters) -> Result<()> {
use colored::Colorize;
use format::Row;
let tfd = params.tfd_model;
let mut tf = params.tf_model;
let output = tfd.get_node_by_id(params.output_node_id)?;
let mut state = tfd.state();
let input = params
.input
.ok_or("Exactly one of <size> or <data> must be specified.")?;
let shape = input
.shape
.iter()
.cloned()
.collect::<Option<Vec<_>>>()
.ok_or("The compare command doesn't support streaming dimensions.")?;
// First generate random values for the inputs.
let mut generated = Vec::new();
for i in params.input_node_ids {
let data = if input.data.is_some() {
input.data.as_ref().unwrap().clone()
} else {
random_tensor(shape.clone(), input.datatype)
};
generated.push((tfd.get_node_by_id(i)?.name.as_str(), data));
}
// Execute the model on tensorflow first.
info!("Running the model on tensorflow.");
let mut tf_outputs = tf.run_get_all(generated.clone())?;
// Execute the model step-by-step on tfdeploy.
state.set_values(generated)?;
let plan = output.eval_order(&tfd)?;
debug!("Using execution plan: {:?}", plan);
let nodes: Vec<_> = tfd.nodes.iter().map(|a| &*a).collect();
let mut display_graph =
::display_graph::DisplayGraph::from_nodes(&*nodes)?.with_graph_def(¶ms.graph)?;
let mut failures = 0;
let hidden = !log_enabled!(Info);
for n in plan {
let node = tfd.get_node_by_id(n)?;
let dn = &mut display_graph.nodes[n];
if node.op_name == "Placeholder" {
dn.hidden = hidden;
continue;
}
let tf_output = tf_outputs.remove(&node.name.to_string()).expect(
format!(
"No node with name {} was computed by tensorflow.",
node.name
).as_str(),
);
match state.compute_one(n) {
Err(e) => {
failures += 1;
dn.more_lines.push(format!("Error message: {:?}", e));
dn.label = Some("ERROR".red().to_string());
dn.hidden = false;
}
_ => {
let tfd_output = state.outputs[n].as_ref().unwrap();
let views = tfd_output.iter().map(|m| &**m).collect::<Vec<&Tensor>>();
match compare_outputs(&tf_output, &views) {
Err(_) => {
failures += 1;
let mismatches = tfd_output
.iter()
.enumerate()
.map(|(n, data)| {
let header = format!("Output {} TFD", n).yellow().bold();
let reason = if n >= tf_output.len() {
"Too many outputs"
} else if tf_output[n].shape() != data.shape() {
"Wrong shape"
} else if !tf_output[n].close_enough(data) {
"Too far away"
} else {
"Other error"
};
let infos = data.partial_dump(false).unwrap();
format!("{} {} {}", header, reason.red().bold().to_string(), infos)
})
.collect::<Vec<_>>();
dn.more_lines.extend(mismatches);
dn.label = Some("MISM.".red().to_string());
dn.hidden = false;
}
_ => {
dn.hidden = hidden;
dn.label = Some("OK".green().to_string());
}
}
}
};
// Use the output from tensorflow to keep tfdeploy from drifting.
for (ix, out) in tf_output.iter().enumerate() {
if dn.outputs.len() > ix {
let edge = &mut display_graph.edges[dn.outputs[ix]];
edge.label = Some(format!("{:?}", out));
}
}
state.set_outputs(node.id, tf_output)?;
}
if failures > 0 {
print_header(format!("There were {} errors:", failures), "red");
display_graph.render(&output_params)?;
} else if log_enabled!(Info) {
display_graph.render(&output_params)?;
} else {
println!("{}", "Each node passed the comparison.".bold().green());
}
Ok(())
}
|
// This file is part of css-purify. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/css-purify/master/COPYRIGHT. No part of css-purify, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2017 The developers of css-purify. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/css-purify/master/COPYRIGHT.
#![warn(missing_docs)]
//! # css-purify
//!
//! This library provides a way to identify and remove unused CSS from stylesheets.
//! It does this by looking for selectors that do not match a provided HTML5 document.
//! Pseudo-elements and psuedo-classes are assumed to always match except for `:empty`, `:root`, `:any-link`, `:link` and `:visited`.
//!
//!
//! ## Getting Started
//!
//!
//! ### Purifying a CSS stylesheet
//!
//! ```
//! extern crate css_purify;
//! use ::css_purify::*;
//! use ::css_purify::html5ever_ext::*;
//! use ::css_purify::html5ever_ext::css::*;
//!
//! let document = RcDom::from_file_path_verified_and_stripped_of_comments_and_processing_instructions_and_with_a_sane_doc_type("/path/to/document.html");
//! let stylesheet = Stylesheet::from_file_path("/path/to/stylesheet.css");
//!
//! // If a CSS rule is unused in all documents (or nodes), then remove it.
//! stylesheet.remove_unused_css_rules(&[&document]);
//!
//! // (Optionally) Save stylesheet
//! stylesheet.to_file_path("/path/to/stylesheet.css");
//!
//! // (Optionally) Inject CSS into document, eg for use in self-contained Google AMP pages.
//! let mut first_style_node = None;
//! rc_dom.find_all_matching_child_nodes_depth_first_including_this_one(&parse_css_selector("head > style[amp]").unwrap(), &mut |node|
//! {
//! first_style_node = Some(node.clone());
//! true
//! });
//! if let Some(ref first_style_node) = first_style_node
//! {
//! first_style_node.append_text(&mut rc_dom, &stylesheet.to_css_string());
//! }
//!```
//!
pub extern crate html5ever_ext;
use ::html5ever_ext::Selectable;
use ::html5ever_ext::css::domain::CssRule;
use ::html5ever_ext::css::domain::HasCssRules;
use ::html5ever_ext::css::domain::selectors::DeduplicatedSelectors;
use ::html5ever_ext::css::domain::selectors::OurSelector;
include!("DeduplicatedSelectorsExt.rs");
include!("HasCssRulesExt.rs");
include!("VecExt.rs");
|
#[macro_use]
extern crate serde_derive;
extern crate toml;
extern crate regex;
extern crate pcre2;
pub mod config;
pub mod rule;
pub mod highlighter;
|
use std::net::TcpStream;
use std::io::Write;
use std::io::BufRead;
use std::io::{BufReader, BufWriter};
fn main() {
let host = "whois.radb.net";
let port = 43;
match TcpStream::connect(format!("{}:{}", host, port)) {
Ok(stream) => {
println!("connected to {}:{}", host, port);
let mut reader = BufReader::new(&stream);
let mut writer = BufWriter::new(&stream);
let msg = format!("AS-GOOGLE\n");
let _ = writer.write(msg.as_bytes());
writer.flush().unwrap();
loop {
let mut line = String::new();
let bytes = reader.read_line(&mut line).unwrap();
if bytes == 0 {
break;
}
println!("{}", line.trim_end());
}
},
Err(e) => {
println!("connection error: {}", e);
}
}
}
|
use crate::format::problem::*;
use crate::format::solution::*;
use crate::helpers::*;
fn create_vehicle_type_with_shift_time_limit(shift_time: f64) -> VehicleType {
VehicleType {
limits: Some(VehicleLimits {
max_distance: None,
shift_time: Some(shift_time),
tour_size: None,
allowed_areas: None,
}),
..create_default_vehicle_type()
}
}
#[test]
fn can_limit_one_job_by_shift_time() {
let problem = Problem {
plan: Plan { jobs: vec![create_delivery_job("job1", vec![100., 0.])], relations: Option::None },
fleet: Fleet {
vehicles: vec![create_vehicle_type_with_shift_time_limit(99.)],
profiles: create_default_matrix_profiles(),
},
..create_empty_problem()
};
let matrix = Matrix {
profile: Some("car".to_owned()),
timestamp: None,
travel_times: vec![1, 100, 100, 1],
distances: vec![1, 1, 1, 1],
error_codes: Option::None,
};
let solution = solve_with_metaheuristic(problem, Some(vec![matrix]));
assert_eq!(
solution,
Solution {
statistic: Statistic {
cost: 0.,
distance: 0,
duration: 0,
times: Timing { driving: 0, serving: 0, waiting: 0, break_time: 0 },
},
tours: vec![],
unassigned: Some(vec![UnassignedJob {
job_id: "job1".to_string(),
reasons: vec![UnassignedJobReason {
code: "SHIFT_TIME_CONSTRAINT".to_string(),
description: "cannot be assigned due to shift time constraint of vehicle".to_string()
}]
}]),
..create_empty_solution()
}
);
}
#[test]
fn can_skip_job_from_multiple_because_of_shift_time() {
let problem = Problem {
plan: Plan {
jobs: vec![
create_delivery_job_with_duration("job1", vec![1., 0.], 10.),
create_delivery_job_with_duration("job2", vec![2., 0.], 10.),
create_delivery_job_with_duration("job3", vec![3., 0.], 10.),
create_delivery_job_with_duration("job4", vec![4., 0.], 10.),
create_delivery_job_with_duration("job5", vec![5., 0.], 10.),
],
relations: Option::None,
},
fleet: Fleet {
vehicles: vec![create_vehicle_type_with_shift_time_limit(40.)],
profiles: create_default_matrix_profiles(),
},
..create_empty_problem()
};
let matrix = create_matrix_from_problem(&problem);
let solution = solve_with_metaheuristic(problem, Some(vec![matrix]));
assert_eq!(
solution,
Solution {
statistic: Statistic {
cost: 52.,
distance: 6,
duration: 36,
times: Timing { driving: 6, serving: 30, waiting: 0, break_time: 0 },
},
tours: vec![Tour {
vehicle_id: "my_vehicle_1".to_string(),
type_id: "my_vehicle".to_string(),
shift_index: 0,
stops: vec![
create_stop_with_activity(
"departure",
"departure",
(0., 0.),
3,
("1970-01-01T00:00:00Z", "1970-01-01T00:00:00Z"),
0
),
create_stop_with_activity(
"job3",
"delivery",
(3., 0.),
2,
("1970-01-01T00:00:03Z", "1970-01-01T00:00:13Z"),
3
),
create_stop_with_activity(
"job2",
"delivery",
(2., 0.),
1,
("1970-01-01T00:00:14Z", "1970-01-01T00:00:24Z"),
4
),
create_stop_with_activity(
"job1",
"delivery",
(1., 0.),
0,
("1970-01-01T00:00:25Z", "1970-01-01T00:00:35Z"),
5
),
create_stop_with_activity(
"arrival",
"arrival",
(0., 0.),
0,
("1970-01-01T00:00:36Z", "1970-01-01T00:00:36Z"),
6
)
],
statistic: Statistic {
cost: 52.,
distance: 6,
duration: 36,
times: Timing { driving: 6, serving: 30, waiting: 0, break_time: 0 },
},
}],
unassigned: Some(vec![
UnassignedJob {
job_id: "job4".to_string(),
reasons: vec![UnassignedJobReason {
code: "SHIFT_TIME_CONSTRAINT".to_string(),
description: "cannot be assigned due to shift time constraint of vehicle".to_string()
}]
},
UnassignedJob {
job_id: "job5".to_string(),
reasons: vec![UnassignedJobReason {
code: "SHIFT_TIME_CONSTRAINT".to_string(),
description: "cannot be assigned due to shift time constraint of vehicle".to_string()
}]
}
]),
..create_empty_solution()
}
);
}
#[test]
// NOTE: this is a specific use case of departure time optimization
#[ignore]
fn can_serve_job_when_it_starts_late() {
let problem = Problem {
plan: Plan {
jobs: vec![create_delivery_job_with_times("job1", vec![1., 0.], vec![(100, 200)], 10.)],
relations: Option::None,
},
fleet: Fleet {
vehicles: vec![create_vehicle_type_with_shift_time_limit(50.)],
profiles: create_default_matrix_profiles(),
},
..create_empty_problem()
};
let matrix = create_matrix_from_problem(&problem);
let solution = solve_with_metaheuristic(problem, Some(vec![matrix]));
assert!(solution.unassigned.is_none());
assert!(!solution.tours.is_empty());
}
|
// Copyright 2019, 2020 Wingchain
//
// 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::HashSet;
use std::sync::Arc;
use node_chain::ChainCommitBlockParams;
use primitives::errors::{Catchable, CommonResult, Display};
use primitives::{
BlockNumber, BuildBlockParams, FullTransaction, Hash, Header, Proof, Transaction,
};
use crate::errors;
use crate::errors::ErrorKind;
use crate::protocol::{BlockData, BodyData};
use crate::stream::StreamSupport;
use crate::support::CoordinatorSupport;
pub struct Verifier<S>
where
S: CoordinatorSupport,
{
support: Arc<StreamSupport<S>>,
}
impl<S> Verifier<S>
where
S: CoordinatorSupport,
{
pub fn new(support: Arc<StreamSupport<S>>) -> CommonResult<Self> {
let verifier = Self { support };
Ok(verifier)
}
}
#[derive(Debug, Display)]
pub enum VerifyError {
/// Block duplicated
#[display(fmt = "Duplicated")]
Duplicated,
/// Block is not the best
#[display(fmt = "Not best")]
NotBest,
/// Bad block
#[display(fmt = "Bad")]
Bad,
/// Invalid execution gap
#[display(fmt = "Invalid execution gap")]
InvalidExecutionGap,
/// Should wait executing
#[display(fmt = "Should wait")]
ShouldWait,
/// Invalid header
#[display(fmt = "Invalid header: {}", _0)]
InvalidHeader(String),
/// Transaction duplicated
#[display(fmt = "Duplicated tx: {}", _0)]
DuplicatedTx(String),
/// Transaction invalid
#[display(fmt = "Invalid tx: {}", _0)]
InvalidTx(node_chain::errors::ValidateTxError),
/// Proof invalid
#[display(fmt = "Invalid proof: {}", _0)]
InvalidProof(String),
}
impl<S> Verifier<S>
where
S: CoordinatorSupport,
{
/// block_data may be taken
pub fn verify_block(
&self,
block_data: &mut Option<BlockData>,
) -> CommonResult<ChainCommitBlockParams> {
{
let block_data_ref = block_data.as_ref().expect("qed");
self.verify_data(block_data_ref)?;
let block_hash = &block_data_ref.block_hash;
let header = block_data_ref.header.as_ref().expect("qed");
self.verify_not_repeat(block_hash)?;
let (_confirmed_number, _confirmed_hash, confirmed_header) =
self.verify_best(header)?;
self.verify_execution(header, &confirmed_header)?;
}
// the following verification need take ownership of block data
let block_data = block_data.take().expect("qed");
let header = block_data.header.expect("qed");
let body = block_data.body.expect("qed");
let proof = block_data.proof.expect("qed");
self.verify_proof(&header, &proof)?;
let (meta_txs, payload_txs) = self.verify_body(body)?;
let commit_block_params = self.verify_header(&header, proof, meta_txs, payload_txs)?;
Ok(commit_block_params)
}
fn verify_data(&self, block_data: &BlockData) -> CommonResult<()> {
let _header = match &block_data.header {
Some(v) => v,
None => return Err(ErrorKind::VerifyError(VerifyError::Bad).into()),
};
let _body = match &block_data.body {
Some(v) => v,
None => return Err(ErrorKind::VerifyError(VerifyError::Bad).into()),
};
let _proof = match &block_data.proof {
Some(v) => v,
None => return Err(ErrorKind::VerifyError(VerifyError::Bad).into()),
};
Ok(())
}
fn verify_not_repeat(&self, block_hash: &Hash) -> CommonResult<()> {
if self.support.ori_support().get_header(block_hash)?.is_some() {
return Err(ErrorKind::VerifyError(VerifyError::Duplicated).into());
}
Ok(())
}
/// Return confirmed block (number, block hash, header)
fn verify_best(&self, header: &Header) -> CommonResult<(BlockNumber, Hash, Header)> {
let confirmed = {
let current_state = &self.support.ori_support().get_current_state();
let confirmed_number = current_state.confirmed_number;
let block_hash = current_state.confirmed_block_hash.clone();
let header = self
.support
.ori_support()
.get_header(&block_hash)?
.ok_or_else(|| {
errors::ErrorKind::Data(format!("Missing header: block_hash: {:?}", block_hash))
})?;
(confirmed_number, block_hash, header)
};
if !(header.number == confirmed.0 + 1 && header.parent_hash == confirmed.1) {
return Err(ErrorKind::VerifyError(VerifyError::NotBest).into());
}
Ok(confirmed)
}
fn verify_execution(&self, header: &Header, confirmed_header: &Header) -> CommonResult<()> {
let current_state = self.support.ori_support().get_current_state();
let system_meta = ¤t_state.system_meta;
if header.payload_execution_gap < 1 {
return Err(ErrorKind::VerifyError(VerifyError::InvalidExecutionGap).into());
}
if header.payload_execution_gap > system_meta.max_execution_gap {
return Err(ErrorKind::VerifyError(VerifyError::InvalidExecutionGap).into());
}
// execution number of the verifying block
let execution_number = header.number - header.payload_execution_gap as u64;
// execution number of the confirmed block
let confirmed_execution_number =
confirmed_header.number - confirmed_header.payload_execution_gap as u64;
if execution_number < confirmed_execution_number {
return Err(ErrorKind::VerifyError(VerifyError::InvalidExecutionGap).into());
}
// execution number of current state
let current_execution_number = current_state.executed_number;
if execution_number > current_execution_number {
return Err(ErrorKind::VerifyError(VerifyError::ShouldWait).into());
}
Ok(())
}
fn verify_proof(&self, header: &Header, proof: &Proof) -> CommonResult<()> {
self.support
.ori_support()
.consensus_verify_proof(header, proof)
.or_else_catch::<node_consensus_base::errors::ErrorKind, _>(|e| match e {
node_consensus_base::errors::ErrorKind::VerifyProofError(e) => Some(Err(
ErrorKind::VerifyError(VerifyError::InvalidProof(e.clone())).into(),
)),
_ => None,
})?;
Ok(())
}
/// Return verified txs (meta_txs, payload_txs)
fn verify_body(
&self,
body: BodyData,
) -> CommonResult<(Vec<Arc<FullTransaction>>, Vec<Arc<FullTransaction>>)> {
let get_verified_txs = |txs: Vec<Transaction>| -> CommonResult<Vec<Arc<FullTransaction>>> {
let mut set = HashSet::new();
let mut result = Vec::with_capacity(txs.len());
for tx in txs {
let tx_hash = self.support.ori_support().hash_transaction(&tx)?;
self.verify_transaction(&tx_hash, &tx, &mut set)?;
let tx = Arc::new(FullTransaction { tx_hash, tx });
result.push(tx);
}
Ok(result)
};
let meta_txs = get_verified_txs(body.meta_txs)?;
let payload_txs = get_verified_txs(body.payload_txs)?;
Ok((meta_txs, payload_txs))
}
/// return commit block params
fn verify_header(
&self,
header: &Header,
proof: Proof,
meta_txs: Vec<Arc<FullTransaction>>,
payload_txs: Vec<Arc<FullTransaction>>,
) -> CommonResult<ChainCommitBlockParams> {
let execution_number = header.number - header.payload_execution_gap as u64;
let build_block_params = BuildBlockParams {
number: header.number,
timestamp: header.timestamp,
meta_txs,
payload_txs,
execution_number,
};
let mut commit_block_params = self.support.ori_support().build_block(build_block_params)?;
if &commit_block_params.header != header {
let msg = format!(
"Invalid header: {:?}, expected: {:?}",
header, commit_block_params.header
);
return Err(ErrorKind::VerifyError(VerifyError::InvalidHeader(msg)).into());
}
commit_block_params.proof = proof;
Ok(commit_block_params)
}
fn verify_transaction(
&self,
tx_hash: &Hash,
tx: &Transaction,
set: &mut HashSet<Hash>,
) -> CommonResult<()> {
if !set.insert(tx_hash.clone()) {
return Err(ErrorKind::VerifyError(VerifyError::DuplicatedTx(format!(
"Duplicated tx: {}",
tx_hash
)))
.into());
}
self.support
.ori_support()
.validate_transaction(tx_hash, &tx, true)
.or_else_catch::<node_chain::errors::ErrorKind, _>(|e| match e {
node_chain::errors::ErrorKind::ValidateTxError(e) => Some(Err(
ErrorKind::VerifyError(VerifyError::InvalidTx(e.clone())).into(),
)),
_ => None,
})?;
Ok(())
}
}
|
use proc_macro::TokenStream;
use proc_macro2::TokenTree;
use std::collections::HashSet;
use syn;
#[derive(Debug)]
pub struct Pattern {
pub struct_name: String,
pub size: String,
pub trimmed_pattern: String,
pub original_pattern: String,
pub tokens: HashSet<char>,
}
#[derive(Default)]
struct Parsed {
struct_name: String,
original_pattern: String,
trimmed_pattern: String,
size: String,
}
impl Pattern {
pub fn from_stream(stream: TokenStream) -> Result<Pattern, String> {
let parsed = Pattern::parse(stream)?;
let tokens = parsed.trimmed_pattern.chars().collect::<HashSet<_>>();
Ok(Pattern {
struct_name: parsed.struct_name,
original_pattern: parsed.original_pattern,
trimmed_pattern: parsed.trimmed_pattern,
size: parsed.size,
tokens,
})
}
fn get_literal(iter: &mut ::proc_macro2::token_stream::IntoIter) -> Result<String, String> {
match iter.next() {
Some(TokenTree::Literal(lit)) => Ok(format!("{}", lit)),
Some(TokenTree::Ident(ident)) => Ok(format!("{}", ident)),
Some(TokenTree::Group(group)) => {
let mut iter = group.stream().into_iter();
Pattern::get_literal(&mut iter)
}
x => Err(format!("Expected literal, got {:?}", x)),
}
}
fn parse(stream: TokenStream) -> Result<Parsed, String> {
let ast: syn::DeriveInput = syn::parse(stream).unwrap();
let mut parsed = Parsed::default();
parsed.struct_name = format!("{}", ast.ident);
for attr in ast.attrs {
let ident = attr
.path
.segments
.iter()
.map(|s| format!("{}", s.ident))
.collect::<Vec<String>>()
.join("::");
if ident == "BitrangeMask" {
let mut iter = attr.tokens.into_iter();
match iter.next() {
Some(TokenTree::Punct(ref p)) if p.as_char() == '=' => {}
x => return Err(format!("Expected '#', got {:?}", x)),
}
let original_pattern = Pattern::get_literal(&mut iter)?;
let original_pattern = original_pattern.trim_matches('"').trim().to_string();
let trimmed_pattern = original_pattern
.chars()
.filter(|c| c.is_alphanumeric())
.collect::<String>();
parsed.original_pattern = original_pattern;
parsed.trimmed_pattern = trimmed_pattern;
} else if ident == "BitrangeSize" {
let mut iter = attr.tokens.into_iter();
match iter.next() {
Some(TokenTree::Punct(ref p)) if p.as_char() == '=' => {}
x => return Err(format!("Expected '#', got {:?}", x)),
}
let size = Pattern::get_literal(&mut iter)?;
parsed.size = size.trim_matches('"').to_string();
}
}
if parsed.trimmed_pattern.is_empty() || parsed.original_pattern.is_empty() {
Err("Missing attribute #[BitrangeMask = \"...\"]".to_string())
} else if parsed.size.is_empty() {
Err("Missing attribute #[BitrangeSize = \"...\"]".to_string())
} else {
Ok(parsed)
}
}
pub fn get_token_mask(&self, token: char) -> String {
let mut str = String::with_capacity(self.original_pattern.len() + 2);
str += "0b";
for c in self.original_pattern.chars() {
str += if c == '_' {
"_"
} else if c == token {
"1"
} else {
"0"
};
}
str
}
pub fn get_token_offset(&self, token: char) -> usize {
self.trimmed_pattern
.chars()
.rev()
.take_while(|c| *c != token)
.count()
}
pub fn get_default_mask(&self) -> String {
let mut str = String::with_capacity(self.original_pattern.len() + 2);
str += "0b";
for c in self.original_pattern.chars() {
str += if c == '_' {
"_"
} else if c == '0' || c == '1' {
"1"
} else {
"0"
}
}
str
}
pub fn get_default_value(&self) -> String {
let mut str = String::with_capacity(self.original_pattern.len() + 2);
str += "0b";
for c in self.original_pattern.chars() {
str += if c == '_' {
"_"
} else if c == '1' {
"1"
} else {
"0"
}
}
str
}
}
|
use std::process::Command;
use web3::types::{Address, U256};
use crypto::sha3::Sha3;
use crypto::digest::Digest;
use secp256k1::{Secp256k1, SecretKey};
use crate::primitive::block::Block;
use bincode::{deserialize};
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BLSKeyStr{
pub sk: String,
pub pkx1: String,
pub pkx2: String,
pub pky1: String,
pub pky2: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct BLSKey{
pub sk: U256,
pub pkx1: U256,
pub pkx2: U256,
pub pky1: U256,
pub pky2: U256,
}
impl BLSKey {
pub fn new(key: BLSKeyStr) -> Self {
BLSKey {
sk :U256::from_dec_str(key.sk.as_ref()).unwrap(),
pkx1 :U256::from_dec_str(key.pkx1.as_ref()).unwrap(),
pkx2 :U256::from_dec_str(key.pkx2.as_ref()).unwrap(),
pky1 :U256::from_dec_str(key.pky1.as_ref()).unwrap(),
pky2 :U256::from_dec_str(key.pky2.as_ref()).unwrap(),
}
}
}
pub fn _encode_sendBlock(block: String, signature: String, new_blk_id: U256) -> Vec<u8> {
let command = format!("./ethabi encode function --lenient ./abi.json sendBlock -p {} -p {} -p {}", block, signature, new_blk_id);
//println!("command {}", command.clone());
let output = Command::new("sh").arg("-c")
.arg(command)
.output().unwrap();
let function_abi = hex::decode(std::str::from_utf8(&output.stdout).unwrap().trim()).unwrap();
return function_abi;
}
pub fn _encode_addScaleNode(address: Address, ip_addr: String, x1: U256, x2: U256, y1: U256, y2: U256) -> Vec<u8> {
let addr = hex::encode(address.as_bytes());
//let addr = addr.replace("0x", "");
let command = format!("./ethabi encode function --lenient ./abi.json addScaleNode -p {} -p {} -p {} -p {} -p {} -p {}", addr, ip_addr, x1, x2, y1, y2);
let output = Command::new("sh").arg("-c")
.arg(command)
.output().unwrap();
//println!("{:?}", output);
let function_abi = hex::decode(std::str::from_utf8(&output.stdout).unwrap().trim()).unwrap();
return function_abi;
}
pub fn _encode_addSideNode(sid: U256, address: Address, ip_addr: String) -> Vec<u8> {
let addr = hex::encode(address.as_bytes());
//let addr = addr.replace("0x", "");
let command = format!("./ethabi encode function --lenient ./abi.json addSideNode -p {} -p {} -p {}", sid, addr, ip_addr);
let output = Command::new("sh").arg("-c")
.arg(command)
.output().unwrap();
// println!("{:?}", output);
let function_abi = hex::decode(std::str::from_utf8(&output.stdout).unwrap().trim()).unwrap();
return function_abi;
}
pub fn _encode_deleteSideNode(sid: U256, tid: U256) -> Vec<u8> {
let command = format!("./ethabi encode function --lenient ./abi.json deleteSideNode -p {} -p {}", sid, tid);
let output = Command::new("sh").arg("-c")
.arg(command)
.output().unwrap();
// println!("{:?}", output);
let function_abi = hex::decode(std::str::from_utf8(&output.stdout).unwrap().trim()).unwrap();
return function_abi;
}
pub fn _encode_submitVote(block: String, sid: U256, bid: U256, sigx: U256, sigy: U256, bitset: U256) -> Vec<u8> {
let command = format!("./ethabi encode function --lenient ./abi.json submitVote -p {:?} -p {} -p {} -p {} -p {} -p {}", block, sid, bid, sigx, sigy, bitset);
//println!("command {}", command.clone());
let output = Command::new("sh").arg("-c")
.arg(command)
.output().unwrap();
let function_abi = hex::decode(std::str::from_utf8(&output.stdout).unwrap().trim()).unwrap();
return function_abi;
}
pub fn _encode_resetSideChain(sid: U256) -> Vec<u8> {
let command = format!("./ethabi encode function --lenient ./abi.json resetSideChain -p {}", sid);
let output = Command::new("sh").arg("-c")
.arg(command)
.output().unwrap();
//println!("{:?}", output);
let function_abi = hex::decode(std::str::from_utf8(&output.stdout).unwrap().trim()).unwrap();
return function_abi;
}
pub fn _encode_resetSideNode(sid: U256) -> Vec<u8> {
let command = format!("./ethabi encode function --lenient ./abi.json deleteSideNode -p {}", sid, );
let output = Command::new("sh").arg("-c")
.arg(command)
.output().unwrap();
//println!("{:?}", output);
let function_abi = hex::decode(std::str::from_utf8(&output.stdout).unwrap().trim()).unwrap();
return function_abi;
}
pub fn _decode_sendBlock(input: &str) -> (String, usize) {
let command = format!("./ethabi decode params -t string -t bytes -t uint256 {}", input);
let output = Command::new("sh").arg("-c")
.arg(command)
.output().unwrap();
let params = std::str::from_utf8(&output.stdout).unwrap().split("\n");
let params: Vec<&str> = params.collect();
//println!("ethabu output {:?}", params);
let block = params[0].replace("string ", "");
let block_id = params[2].replace("uint256 ", "");
let block_id = usize::from_str_radix(&block_id, 16).unwrap();
(block, block_id)
}
pub fn _sign_bls(msg: String, key_file: String, bin_path: &str) -> (String, String) {
let command = bin_path.to_string() + &format!( "/sign -msg={} -key={}", msg, key_file);
//info!("command {}", command.clone());
let output = Command::new("sh").arg("-c")
.arg(command)
.output().unwrap();
//let function_abi = hex::decode(std::str::from_utf8(&output.stdout).unwrap().trim()).unwrap();
let sig = std::str::from_utf8(&output.stdout).unwrap().split("\n");
let sig: Vec<&str> = sig.collect();
return (sig[0].to_string(), sig[1].to_string());
}
//pub fn _aggregate_sig(x1: String, y1: String, x2: String, y2: String)-> (String, String) {
//let command = format!("./aggregate -x1={} -y1={} -x2={} -y2={}", x1, y1, x2, y2);
//println!("command {}", command.clone());
//let output = Command::new("sh").arg("-c")
//.arg(command)
//.output().unwrap();
////let function_abi = hex::decode(std::str::from_utf8(&output.stdout).unwrap().trim()).unwrap();
//let sig = std::str::from_utf8(&output.stdout).unwrap().split("\n");
//let sig: Vec<&str> = sig.collect();
//return (sig[0].to_string(), sig[1].to_string());
//}
pub fn _aggregate_sig(x1: String, y1: String, x2: String, y2: String, bin_dir: &str)-> (String, String) {
let command = bin_dir.to_string() + &format!("/aggregate -x1={} -y1={} -x2={} -y2={}", x1, y1, x2, y2);
//info!("command {}", command.clone());
let output = Command::new("sh").arg("-c")
.arg(command)
.output().unwrap();
//let function_abi = hex::decode(std::str::from_utf8(&output.stdout).unwrap().trim()).unwrap();
let sig = std::str::from_utf8(&output.stdout).unwrap().split("\n");
let sig: Vec<&str> = sig.collect();
return (sig[0].to_string(), sig[1].to_string());
}
pub fn _hash_message(message: &[u8], result: &mut [u8]) {
let s = String::from("\x19Ethereum Signed Message:\n32");
let prefix = s.as_bytes();
let prefixed_message = [prefix, message].concat();
let mut hasher = Sha3::keccak256();
hasher.input(&prefixed_message);
hasher.result(result);
}
pub fn hash_header(message: &[u8], result: &mut [u8]) {
let mut hasher = Sha3::keccak256();
hasher.input(message);
hasher.result(result);
}
pub fn hash_header_hex(message: &[u8]) -> String {
let mut result: [u8; 32] = [0; 32];
let mut hasher = Sha3::keccak256();
hasher.input(message);
hasher.result(&mut result);
let hash_str = hex::encode(&result);
hash_str
}
pub fn _sign_block(block: &str, private_key: &[u8]) -> String {
let mut hasher = Sha3::keccak256();
hasher.input_str(block);
let mut message = [0; 32];
hasher.result(&mut message);
let mut result = [0u8; 32];
_hash_message(&message, &mut result);
let secp = Secp256k1::new();
let sk = SecretKey::from_slice(private_key).unwrap();
let msg = secp256k1::Message::from_slice(&result).unwrap();
let sig = secp.sign_recoverable(&msg, &sk);
let (v, data) = sig.serialize_compact();
let mut r: [u8; 32] = [0; 32];
let mut s: [u8; 32] = [0; 32];
r.copy_from_slice(&data[0..32]);
s.copy_from_slice(&data[32..64]);
return format!("{}{}{}", hex::encode(r), hex::encode(s), hex::encode([v.to_i32() as u8 + 27]));
}
pub fn _convert_u256(value: U256) -> ethereum_types::U256 {
let U256(ref arr) = value;
let mut ret = [0; 4];
ret[0] = arr[0];
ret[1] = arr[1];
ethereum_types::U256(ret)
}
pub fn _get_key_as_H256(key: String) -> ethereum_types::H256 {
let private_key = _get_key_as_vec(key);
ethereum_types::H256(_to_array(private_key.as_slice()))
}
pub fn _get_key_as_vec(key: String) -> Vec<u8> {
let key = key.replace("0x", "");
hex::decode(&key).unwrap()
}
pub fn _to_array(bytes: &[u8]) -> [u8; 32] {
let mut array = [0; 32];
let bytes = &bytes[..array.len()];
array.copy_from_slice(bytes);
array
}
pub fn _block_to_str(block: Block) -> String {
let block_vec: Vec<u8> = block.clone().ser();
let block_ref: &[u8] = block_vec.as_ref();
hex::encode(block_ref)
}
pub fn _str_to_block(block_str: String) -> Block {
let bytes = match hex::decode(&block_str) {
Ok(b) => b,
Err(e) => {
println!("unable to decode block_ser");
let mut block = Block::default();
return block;
}
};
match bincode::deserialize(&bytes[..]) {
Ok(block) => block,
Err(e) => {
println!("unable to deserialize block");
Block::default()
},
}
}
pub fn _generate_random_header() -> String {
let mut header = String::new();
for i in {0..8} {
header = format!("{}{}", header, hex::encode(web3::types::H256::random().as_bytes()))
}
header
}
pub fn _count_sig(x: usize) -> usize {
let mut cnt = 0;
let mut t = x;
while t > 0 {
if t.clone() % 2 == 1 {
cnt += 1;
}
t /= 2;
}
cnt
}
|
use self::query_plan_node::node_id::QueryPlanNodeId;
pub(crate) mod query_plan_node;
/// Query plan tree.
/// This tree is a binary tree because every SELECT operation can break down into unary or binary operations.
#[derive(Clone, PartialEq, Debug, new)]
pub(crate) struct QueryPlanTree {
pub(crate) root: QueryPlanNodeId,
}
|
// Shields clippy errors in generated bundled.rs
#![allow(clippy::unreadable_literal)]
mod template;
pub use self::template::{
TemplateContext, AVAILABLE_SPECS, DEFAULT_P2P_PORT, DEFAULT_RPC_PORT, DEFAULT_SPEC,
};
pub use std::io::{Error, Result};
use self::template::Template;
use numext_fixed_hash::H256;
use std::borrow::Cow;
use std::fmt;
use std::fs;
use std::io::{self, BufReader, Read};
use std::path::{Path, PathBuf};
use tempfile::NamedTempFile;
include!(concat!(env!("OUT_DIR"), "/bundled.rs"));
include!(concat!(env!("OUT_DIR"), "/code_hashes.rs"));
pub const CKB_CONFIG_FILE_NAME: &str = "ckb.toml";
pub const MINER_CONFIG_FILE_NAME: &str = "ckb-miner.toml";
pub const SPEC_DEV_FILE_NAME: &str = "specs/dev.toml";
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Resource {
Bundled(String),
FileSystem(PathBuf),
}
impl fmt::Display for Resource {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Resource::Bundled(key) => write!(f, "Bundled({})", key),
Resource::FileSystem(path) => write!(f, "FileSystem({})", path.display()),
}
}
}
impl Resource {
pub fn is_bundled(&self) -> bool {
match self {
Resource::Bundled(_) => true,
_ => false,
}
}
/// Gets resource content
pub fn get(&self) -> Result<Cow<'static, [u8]>> {
match self {
Resource::Bundled(key) => BUNDLED.get(key),
Resource::FileSystem(path) => {
let mut file = BufReader::new(fs::File::open(path)?);
let mut data = Vec::new();
file.read_to_end(&mut data)?;
Ok(Cow::Owned(data))
}
}
}
/// Gets resource input stream
pub fn read(&self) -> Result<Box<dyn Read>> {
match self {
Resource::Bundled(key) => BUNDLED.read(key),
Resource::FileSystem(path) => Ok(Box::new(BufReader::new(fs::File::open(path)?))),
}
}
}
pub struct ResourceLocator {
root_dir: PathBuf,
}
impl ResourceLocator {
pub fn root_dir(&self) -> &Path {
self.root_dir.as_path()
}
/// Creates a ResourceLocator using `path` as root directory.
///
/// It returns error if the directory does not exists and current user has no permission to create it.
pub fn with_root_dir(root_dir: PathBuf) -> Result<ResourceLocator> {
fs::create_dir_all(&root_dir)?;
Ok(ResourceLocator { root_dir })
}
pub fn current_dir() -> Result<ResourceLocator> {
let root_dir = ::std::env::current_dir()?;
Ok(ResourceLocator { root_dir })
}
pub fn ckb(&self) -> Resource {
self.resolve(PathBuf::from(CKB_CONFIG_FILE_NAME)).unwrap()
}
pub fn miner(&self) -> Resource {
self.resolve(PathBuf::from(MINER_CONFIG_FILE_NAME)).unwrap()
}
/// Resolves a resource using a path.
///
/// The path may be absolute or relative. This function tries the file system first. If the file
/// is absent in the file system and it is relative, the function will search in the bundled files.
///
/// The relative path is relative to the resource root directory.
///
/// All the bundled files are assumed in the resource root directory.
///
/// It returns None when no resource with the path is found.
pub fn resolve(&self, path: PathBuf) -> Option<Resource> {
if path.is_absolute() {
return file_system(path);
}
file_system(self.root_dir.join(&path)).or_else(|| bundled(path))
}
/// Resolves a resource using a path as the path is refered in the resource `relative_to`.
///
/// This function is similar to [`ResourceLocator::resolve`]. The difference is how to resolve a relative path.
///
/// [`ResourceLocator::resolve`]: struct.ResourceLocator.html#method.open
///
/// The relative path is relative to the directory containing the resource `relative_to`.
///
/// For security reason, when `relative_to` is `Resource::Bundled`, the return value is either
/// `Some(Resource::Bundled)` or `None`. A bundled file is forbidden to reference a file in the
/// file system.
pub fn resolve_relative_to(&self, path: PathBuf, relative_to: &Resource) -> Option<Resource> {
match relative_to {
Resource::Bundled(key) => {
// Bundled file can only refer to bundled files.
let relative_start_dir = parent_dir(PathBuf::from(key)).join(&path);
bundled(relative_start_dir)
}
Resource::FileSystem(relative_to_path) => {
if path.is_absolute() {
return file_system(path);
}
let start_dir = parent_dir(relative_to_path.clone());
file_system(start_dir.join(&path)).or_else(|| {
start_dir
.strip_prefix(&self.root_dir)
.ok()
.and_then(|relative_start_dir| bundled(relative_start_dir.join(path)))
})
}
}
}
pub fn exported(&self) -> bool {
BUNDLED
.file_names()
.any(|name| self.root_dir.join(name).exists())
}
pub fn export_ckb<'a>(&self, context: &TemplateContext<'a>) -> Result<()> {
self.export(CKB_CONFIG_FILE_NAME, context)
}
pub fn export_miner<'a>(&self, context: &TemplateContext<'a>) -> Result<()> {
self.export(MINER_CONFIG_FILE_NAME, context)
}
pub fn export<'a>(&self, name: &str, context: &TemplateContext<'a>) -> Result<()> {
let target = self.root_dir.join(name);
let resource = Resource::Bundled(name.to_string());
let template = Template::new(from_utf8(resource.get()?)?);
let mut out = NamedTempFile::new_in(&self.root_dir)?;
if name.contains('/') {
if let Some(dir) = target.parent() {
fs::create_dir_all(dir)?;
}
}
template.write_to(&mut out, context)?;
out.persist(target)?;
Ok(())
}
}
#[cfg(windows)]
fn path_as_key(path: &PathBuf) -> Cow<str> {
Cow::Owned(path.to_string_lossy().replace("\\", "/"))
}
#[cfg(not(windows))]
fn path_as_key(path: &PathBuf) -> Cow<str> {
path.to_string_lossy()
}
fn file_system(path: PathBuf) -> Option<Resource> {
if path.exists() {
Some(Resource::FileSystem(path))
} else {
None
}
}
pub fn bundled(path: PathBuf) -> Option<Resource> {
let key = path_as_key(&path);
if BUNDLED.is_available(&key) {
Some(Resource::Bundled(key.into_owned()))
} else {
None
}
}
fn parent_dir(mut path: PathBuf) -> PathBuf {
path.pop();
path
}
fn from_utf8(data: Cow<[u8]>) -> Result<String> {
String::from_utf8(data.to_vec()).map_err(|err| Error::new(io::ErrorKind::Other, err))
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::path::{Path, PathBuf};
fn mkdir() -> tempfile::TempDir {
tempfile::Builder::new()
.prefix("ckb_resource_test")
.tempdir()
.unwrap()
}
fn touch<P: AsRef<Path>>(path: P) -> PathBuf {
fs::create_dir_all(path.as_ref().parent().unwrap()).expect("create dir in test");
fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.expect("touch file in test");
path.as_ref().to_path_buf()
}
#[test]
fn test_resource_locator_resolve() {
let dir = mkdir();
let spec_dev_path = touch(dir.path().join("specs/dev.toml"));
let locator = ResourceLocator::with_root_dir(dir.path().to_path_buf())
.expect("resource root dir exists");
assert_eq!(
locator.resolve("ckb.toml".into()),
Some(Resource::Bundled("ckb.toml".into()))
);
assert_eq!(
locator.resolve("specs/testnet.toml".into()),
Some(Resource::Bundled("specs/testnet.toml".into()))
);
assert_eq!(
locator.resolve("specs/dev.toml".into()),
Some(Resource::FileSystem(spec_dev_path.clone()))
);
assert_eq!(locator.resolve(dir.path().join("ckb.toml")), None);
assert_eq!(locator.resolve("x.toml".into()), None);
}
#[test]
fn test_resource_locator_resolve_relative_to() {
let dir = mkdir();
let spec_dev_path = touch(dir.path().join("specs/dev.toml"));
let locator = ResourceLocator::with_root_dir(dir.path().to_path_buf())
.expect("resource root dir exists");
// Relative to Bundled("ckb.toml")
{
let ckb = Resource::Bundled("ckb.toml".into());
assert_eq!(
locator.resolve_relative_to("specs/dev.toml".into(), &ckb),
Some(Resource::Bundled("specs/dev.toml".into()))
);
assert_eq!(
locator.resolve_relative_to("specs/testnet.toml".into(), &ckb),
Some(Resource::Bundled("specs/testnet.toml".into()))
);
assert_eq!(locator.resolve_relative_to("x".into(), &ckb), None);
assert_eq!(
locator.resolve_relative_to("cells/always_success".into(), &ckb),
None,
);
assert_eq!(
locator.resolve_relative_to(spec_dev_path.clone(), &ckb),
None,
);
}
// Relative to Bundled("specs/dev.toml")
{
let ckb = Resource::Bundled("specs/dev.toml".into());
assert_eq!(
locator.resolve_relative_to("cells/secp256k1_blake160_sighash_all".into(), &ckb),
Some(Resource::Bundled(
"specs/cells/secp256k1_blake160_sighash_all".into()
))
);
assert_eq!(locator.resolve_relative_to("x".into(), &ckb), None);
assert_eq!(
locator.resolve_relative_to("cells/always_success".into(), &ckb),
None,
);
}
// Relative to FileSystem("specs/dev.toml")
{
let spec_dev = Resource::FileSystem(spec_dev_path.clone());
assert_eq!(
locator
.resolve_relative_to("cells/secp256k1_blake160_sighash_all".into(), &spec_dev),
Some(Resource::Bundled(
"specs/cells/secp256k1_blake160_sighash_all".into()
))
);
assert_eq!(locator.resolve_relative_to("x".into(), &spec_dev), None);
assert_eq!(
locator.resolve_relative_to("cells/always_success".into(), &spec_dev),
None,
);
assert_eq!(
locator.resolve_relative_to(dir.path().join("ckb.toml"), &spec_dev),
None,
);
}
}
}
|
use hydroflow::{hydroflow_syntax, var_args};
#[hydroflow::main]
async fn main() {
let mut df = hydroflow_syntax! {
// Should be a `Duration`.
source_interval(5) -> for_each(std::mem::drop);
};
df.run_async().await;
}
|
use super::super::characters::Character;
use super::super::boosters::Booster;
use super::super::moves::Move;
/// A request to the user for an `Answer`.
///
/// This is how input is obtained.
/// Every question is associated with a context (information that helps the user in answering the question).
/// The context is stored in the variant fields.
pub enum Question {
ChooseCharacter {
available_characters: Vec<Character>,
},
ChooseBooster {
available_boosters: Vec<Booster>,
},
ChooseMove {
available_moves: Vec<Move>
},
}
|
#![no_std]
#![no_main]
#![feature(trait_alias)]
#![feature(min_type_alias_impl_trait)]
#![feature(impl_trait_in_bindings)]
#![feature(type_alias_impl_trait)]
#![allow(incomplete_features)]
#[path = "../example_common.rs"]
mod example_common;
use embassy_stm32::gpio::{Level, Output, Speed};
use embedded_hal::digital::v2::OutputPin;
use example_common::*;
use cortex_m_rt::entry;
use embassy_stm32::spi::{Config, Spi};
use embassy_stm32::time::Hertz;
use embedded_hal::blocking::spi::Transfer;
use stm32l4::stm32l4x5 as pac;
#[entry]
fn main() -> ! {
info!("Hello World, dude!");
let pp = pac::Peripherals::take().unwrap();
pp.DBGMCU.cr.modify(|_, w| {
w.dbg_sleep().set_bit();
w.dbg_standby().set_bit();
w.dbg_stop().set_bit()
});
pp.RCC.ahb2enr.modify(|_, w| {
w.gpioaen().set_bit();
w.gpioben().set_bit();
w.gpiocen().set_bit();
w.gpioden().set_bit();
w.gpioeen().set_bit();
w.gpiofen().set_bit();
w
});
let p = embassy_stm32::init(Default::default());
let mut spi = Spi::new(
p.SPI3,
p.PC10,
p.PC12,
p.PC11,
Hertz(1_000_000),
Config::default(),
);
let mut cs = Output::new(p.PE0, Level::High, Speed::VeryHigh);
loop {
let mut buf = [0x0A; 4];
unwrap!(cs.set_low());
unwrap!(spi.transfer(&mut buf));
unwrap!(cs.set_high());
info!("xfer {=[u8]:x}", buf);
}
}
|
#[doc = "Register `SECBOOTADD0R` reader"]
pub type R = crate::R<SECBOOTADD0R_SPEC>;
#[doc = "Register `SECBOOTADD0R` writer"]
pub type W = crate::W<SECBOOTADD0R_SPEC>;
#[doc = "Field `BOOT_LOCK` reader - BOOT_LOCK"]
pub type BOOT_LOCK_R = crate::BitReader;
#[doc = "Field `BOOT_LOCK` writer - BOOT_LOCK"]
pub type BOOT_LOCK_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>;
#[doc = "Field `SECBOOTADD0` writer - SECBOOTADD0"]
pub type SECBOOTADD0_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 25, O, u32>;
impl R {
#[doc = "Bit 0 - BOOT_LOCK"]
#[inline(always)]
pub fn boot_lock(&self) -> BOOT_LOCK_R {
BOOT_LOCK_R::new((self.bits & 1) != 0)
}
}
impl W {
#[doc = "Bit 0 - BOOT_LOCK"]
#[inline(always)]
#[must_use]
pub fn boot_lock(&mut self) -> BOOT_LOCK_W<SECBOOTADD0R_SPEC, 0> {
BOOT_LOCK_W::new(self)
}
#[doc = "Bits 7:31 - SECBOOTADD0"]
#[inline(always)]
#[must_use]
pub fn secbootadd0(&mut self) -> SECBOOTADD0_W<SECBOOTADD0R_SPEC, 7> {
SECBOOTADD0_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "FFlash secure boot address 0 register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`secbootadd0r::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`secbootadd0r::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct SECBOOTADD0R_SPEC;
impl crate::RegisterSpec for SECBOOTADD0R_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`secbootadd0r::R`](R) reader structure"]
impl crate::Readable for SECBOOTADD0R_SPEC {}
#[doc = "`write(|w| ..)` method takes [`secbootadd0r::W`](W) writer structure"]
impl crate::Writable for SECBOOTADD0R_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets SECBOOTADD0R to value 0"]
impl crate::Resettable for SECBOOTADD0R_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::er::{self, Result};
use crate::git;
use crate::server;
use crate::utils::{self, CliEnv};
use failure::{format_err, Error};
use futures::{
future::{self, Either},
Future,
};
use serde::{Deserialize, Serialize};
use server::SshConn;
use std::io;
use std::path::PathBuf;
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ProjectConfig {
pub name: String,
pub git_user: String,
pub git_repo_uri: String,
pub git_backup_repo: String,
pub server_name: Option<String>,
pub domain: Option<String>,
}
impl ProjectConfig {
/// Return project dir
pub fn dir(&self, env: &CliEnv) -> PathBuf {
project_dir(env, &self.name)
}
/// Returns project dir with extra joined onto it
pub fn dir_and(&self, env: &CliEnv, extra: &str) -> PathBuf {
let mut path = project_dir(env, &self.name);
path.push(extra);
path
}
/// Gets server config of project, or optionally creates
pub fn get_server(
&mut self,
env: &CliEnv,
or_create: bool,
) -> Result<Option<server::ServerConfig>> {
match &self.server_name {
Some(server_name) => server::get_config(env, server_name).map(Some),
None => {
if or_create {
// todo: Select whether to create
println!("No server registered, you can create one");
let servers = server::get_servers(env)?;
use utils::SelectOrAdd;
match env.select_or_add("Server", &servers, None)? {
SelectOrAdd::Selected(idx) => {
let server_name = servers
.get(idx)
.ok_or_else(|| er::Custom::msg("Could not find server index"))?;
self.server_name = Some(server_name.clone());
self.write_config(env)?;
Ok(Some(server::get_config(env, server_name)?))
}
SelectOrAdd::AddNew => {
let server_config = server::add_server(env)?;
self.server_name = Some(server_config.name.clone());
self.write_config(env)?;
Ok(Some(server_config))
}
}
} else {
Ok(None)
}
}
}
}
/// Can be used when a server is required,
/// will get the current server, or when not specified, allow to
/// define one
pub fn require_server(&mut self, env: &CliEnv) -> Result<server::ServerConfig> {
let server_opt = self.get_server(env, true)?;
match server_opt {
Some(server) => Ok(server),
None => Err(er::Custom::msg("Project server required").into()),
}
}
pub fn write_config(&self, env: &CliEnv) -> Result<()> {
let content_str = serde_json::to_string_pretty(&self)?;
// Todo: Consider keeping some in <project>/.project
// Possibly this should be done after git setup after
// this function, but might also be advantages saving the
// data. The logic should handle it if re-running
env.config_dirs.projects.write(&self.name, &content_str)?;
Ok(())
}
/// Writes to a file given a path relative to
/// project root
pub fn write_file(&self, env: &CliEnv, file: &str, content: &str) -> Result<()> {
let mut file_path = self.dir(env);
file_path.push(file);
utils::write_file(&file_path, content)
}
}
pub fn has_config(env: &CliEnv, project: &str) -> bool {
env.config_dirs.projects.has_file(project)
}
/// Resolves current project interactive, either
/// by figuring it out from the current directory,
/// or asking the user to select one
// todo: Possibly make ProjEnv over CliEnv
// (not so composy)
// or something lessen boilerplate a little
// shorter name
pub fn resolve_current_project_interactive(env: &CliEnv) -> Result<ProjectConfig> {
match resolve_current_project(env) {
Ok(project_confir) => Ok(project_confir),
Err(_e) => {
// Todo: Could allow init here if in appropriate directory
let projects = get_projects(env)?;
// A little speculative, but for now, auto select
// project if there is only one
if projects.len() == 1 {
println!("Only one project, selecting {}!", projects[0]);
get_config(env, &projects[0])
} else {
env.select("Select project", &projects, None)
.and_then(|i| match projects.get(i) {
Some(project_name) => get_config(env, project_name),
None => er::err("Error selecting project"),
})
}
}
}
}
/// Resolve project from current directory, or error
pub fn resolve_current_project(env: &CliEnv) -> Result<ProjectConfig> {
let cd = std::env::current_dir()?;
let cd = cd
.strip_prefix(&env.projects_dir)
.map_err(|e| er::error(format!("{:?}", e)))?;
// Then use first component
match cd.components().next() {
Some(std::path::Component::Normal(os_str)) => {
match get_config(env, &os_str.to_string_lossy()) {
Ok(project_config) => Ok(project_config),
Err(e) => er::err(format!("Could not resolve project config: {:?}", e)),
}
}
_ => er::err("Could not resolve project dir"),
}
}
pub fn get_config(env: &CliEnv, project: &str) -> Result<ProjectConfig> {
let json_file = std::fs::File::open(env.config_dirs.projects.filepath(project))?;
let buf_reader = io::BufReader::new(json_file);
let config = serde_json::from_reader::<_, ProjectConfig>(buf_reader)?;
Ok(config)
}
/// Returns names of projects
pub fn get_projects(env: &CliEnv) -> Result<Vec<String>> {
utils::files_in_dir(&env.config_dirs.projects.0)
}
pub fn project_dir(env: &CliEnv, project: &str) -> PathBuf {
env.get_project_path(project)
}
fn init_project_config(env: &CliEnv) -> Result<(ProjectConfig, git::InspectGit)> {
let name = env.get_input("Project name", None)?;
let current_config = if has_config(env, &name) {
println!("Project config exists for: {}", &name);
println!("Modifying entry.");
Some(get_config(env, &name)?)
} else {
println!(
"Project config does not exist, collecting data for: {}",
&name
);
None
};
// Git account
let git_account =
git::select_account(env, current_config.as_ref().map(|c| c.git_user.to_owned()))?;
let git_user = git_account.user.clone();
// Git repo
let project_git = git::inspect_git(project_dir(env, &name))?;
// Todo: !! Prevent tokened url when modifiying entry
let git_repo_uri = match project_git.origin_url.as_ref() {
Some(origin_url) => {
println!(
"Get repo uri (from existing origin): {}",
console::style(origin_url).magenta()
);
origin_url.to_owned()
}
None => {
let user_uri = format!("https://github.com/{}", &git_user);
let mut repo_type_options = vec![
format!(
"User repo ({})",
console::style(user_uri.clone() + "/..").dim()
),
"Repo uri (user or existing)".to_string(),
];
let default = match current_config.as_ref() {
Some(current_config) => {
repo_type_options.push(format!("Current: {}", ¤t_config.git_repo_uri));
Some(2)
}
None => None,
};
let repo_type = env.select("Repo uri", &repo_type_options, default)?;
// todo: Remove after select?
// better to insert user repo as default input, not sure how
match repo_type {
0 => {
// User repo
let repo_name = env.get_input(&format!("User repo {}/", &user_uri), None)?;
format!("{}/{}", &user_uri, &repo_name)
}
1 => {
// Full repo uri
env.get_input("Repo uri", None)?
}
_ => return Err(er::Custom::msg("Unrecognized select").into()),
}
}
};
// Backup repo
// Server
let servers = server::get_servers(&env)?;
let server_name = env
.select_or_add_or_none(
"Server",
&servers,
current_config.as_ref().and_then(|c| {
c.server_name
.as_ref()
.and_then(|server_name| servers.iter().position(|e| e == server_name))
}),
)
.and_then(|selected| {
use utils::SelectOrAddOrNone;
match selected {
SelectOrAddOrNone::Selected(index) => servers
.get(index)
.ok_or_else(|| {
format_err!("Mismatched index when getting server: {}", index).into()
})
.map(|name| Some(name.to_owned())),
SelectOrAddOrNone::AddNew => Ok(Some(server::add_server(env)?.name)),
SelectOrAddOrNone::None => Ok(None),
}
})?;
let domain = env
.get_input(
"Domain name",
current_config.as_ref().and_then(|c| c.domain.to_owned()),
)
.map(|domain| {
let domain = domain.trim();
if domain.len() > 0 {
Some(domain.to_string())
} else {
None
}
})?;
// todo: This could possibly be improved. Could there be an existing backup dir?
// It is also possible a non-user repo is selected, in which case this would break it
let git_backup_repo = git_repo_uri.clone() + "-backup";
let config = ProjectConfig {
name,
git_repo_uri,
git_backup_repo,
git_user,
server_name,
domain,
};
println!("{:?}", &config);
config.write_config(env)?;
Ok((config, project_git))
}
// Not ideally, but split initially with init_project_config
// to avoid type complexity with future and io:Result
pub fn init_cmd<'a>(env: &'a CliEnv) -> impl Future<Item = (), Error = Error> + 'a {
let (config, project_git) = match init_project_config(env) {
Ok(config) => config,
Err(io_err) => return Either::A(future::err(Error::from(io_err))),
};
// Get projects git account
let git_config = match git::get_config(env, &config.git_user) {
Ok(git_config) => git_config,
Err(io_err) => return Either::A(future::err(Error::from(io_err))),
};
Either::B(
git::setup_git_dir(
env,
project_git,
git_config.clone(),
config.git_repo_uri.clone(),
)
.and_then(move |_| {
git::do_create_remote(env, git_config, config.git_backup_repo).map(|_| ())
}),
)
}
pub fn code(env: &CliEnv, project: &ProjectConfig) -> Result<()> {
use std::process::Command;
let project_dir = project.dir(env);
std::env::set_current_dir(&project_dir)?;
let mut cmd = Command::new("code");
cmd.arg(".");
cmd.spawn()?;
Ok(())
}
pub fn add_commit_push_git(env: &CliEnv, project: &ProjectConfig) -> Result<()> {
let project_dir = project.dir(env);
let dir_git = git::inspect_git(project_dir.clone())?;
let repo = match dir_git.repo {
Some(repo) => repo,
None => {
// todo: propose run init
println!("No repository found in project: {}", project.name);
return er::err("No repo");
}
};
std::env::set_current_dir(&project_dir)?;
let tree = git::add_all(&repo)?;
let default_msg = format!("Project commit: {}", utils::now_formatted());
let message = env.get_input("Message", Some(default_msg))?;
git::commit(&repo, tree, &message)?;
git::push_origin_master(&repo)?;
println!("Commit and push to origin successful");
Ok(())
}
/// Prod container command through ssh, or local prod
pub fn prod(
env: &CliEnv,
project: &mut ProjectConfig,
user_args: Vec<String>,
on_server: bool,
) -> Result<()> {
prod_cmds(env, project, vec![user_args], on_server)
}
/// Prod container command through ssh
pub fn prod_cmds(
env: &CliEnv,
project: &mut ProjectConfig,
cmds: Vec<Vec<String>>,
on_server: bool,
) -> Result<()> {
// Create command args
use crate::docker::ComposeCmd;
// Especially for local, there should be a different name for prod than dev
let compose_name = format!("{}-prod", project.name);
let mut compose_cmd = if on_server {
ComposeCmd::server(compose_name)
} else {
ComposeCmd::local(env, compose_name)
};
compose_cmd
.workdir_file("base/docker-compose.yml")
.workdir_file("prod/docker-compose.prod.yml");
if on_server {
let server = match project.get_server(env, true)? {
Some(server) => server,
None => {
return Err(format_err!(
"Missing server in project config, required for prod on server"
))
}
};
let conn = SshConn::connect_server(env, &server)?;
let cd = format!(
"cd {}/projects/{}",
server.home_dir().to_string_lossy(),
project.name
);
for user_args in cmds.into_iter() {
let mut compose_cmd = compose_cmd.clone();
// Apply user_args or default to "up"
if user_args.len() > 0 {
compose_cmd.user_args(user_args);
}
// Run compose command
conn.exec(format!(
"{}; docker-compose {}",
cd,
compose_cmd.to_args().join(" ")
))?;
}
} else {
// Run prod locally
// todo: Maybe there should just be a dedicated function for local
/*
crate::wp::create_docker_local_prod_yml(env, project)?;
compose_cmd.relative_file("docker/prod-local.yml");
crate::wp::create_wp_mounts_docker_yml(env, project)?;
compose_cmd.relative_file("docker/mounts.yml");
*/
let project_dir = project.dir(env);
println!("{:?}", project_dir);
std::env::set_current_dir(project_dir)?;
for user_args in cmds.into_iter() {
let mut compose_cmd = compose_cmd.clone();
// Apply user_args or default to "up"
if user_args.len() > 0 {
compose_cmd.user_args(user_args);
}
// Run compose command
// By default, the command inherits stdin, out, err
// when used with .spawn()
let mut cmd = std::process::Command::new("docker-compose");
let cmd_args = compose_cmd.to_args();
println!("{:?}", cmd_args);
cmd.args(cmd_args);
cmd.spawn()?;
}
}
Ok(())
}
|
use crate::enums::{
Align, CallbackTrigger, Color, ColorDepth, Cursor, Damage, Event, Font, FrameType, LabelType,
Shortcut,
};
use std::convert::From;
use std::{fmt, io};
/// Error types returned by fltk-rs + wrappers of std errors
#[derive(Debug)]
pub enum FltkError {
/// i/o error
IoError(io::Error),
/// Null string conversion error
NullError(std::ffi::NulError),
/// Internal fltk error
Internal(FltkErrorKind),
/// Error using an errorneous env variable
EnvVarError(std::env::VarError),
/// Unknown error
Unknown(String),
}
unsafe impl Send for FltkError {}
unsafe impl Sync for FltkError {}
/// Error kinds enum for `FltkError`
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum FltkErrorKind {
/// Failed to run the application
FailedToRun,
/// Failed to initialize the multithreading
FailedToLock,
/// Failed to set the general scheme of the application
FailedToSetScheme,
/// Failed operation, mostly unknown reason!
FailedOperation,
/// System resource (file, image) not found
ResourceNotFound,
/// Image format error when opening an image of an unsopported format
ImageFormatError,
/// Error filling table
TableError,
/// Error due to printing
PrintError,
}
impl std::error::Error for FltkError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
FltkError::IoError(err) => Some(err),
FltkError::NullError(err) => Some(err),
_ => None,
}
}
}
impl fmt::Display for FltkError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
FltkError::IoError(ref err) => err.fmt(f),
FltkError::NullError(ref err) => err.fmt(f),
FltkError::Internal(ref err) => write!(f, "An internal error occured {:?}", err),
FltkError::EnvVarError(ref err) => write!(f, "An env var error occured {:?}", err),
FltkError::Unknown(ref err) => write!(f, "An unknown error occurred {:?}", err),
}
}
}
impl From<io::Error> for FltkError {
fn from(err: io::Error) -> FltkError {
FltkError::IoError(err)
}
}
impl From<std::ffi::NulError> for FltkError {
fn from(err: std::ffi::NulError) -> FltkError {
FltkError::NullError(err)
}
}
impl From<std::env::VarError> for FltkError {
fn from(err: std::env::VarError) -> FltkError {
FltkError::EnvVarError(err)
}
}
/// A trait defined for all enums passable to the `WidgetExt::set_type()` method
pub trait WidgetType {
/// Get the integral representation of the widget type
fn to_i32(self) -> i32;
/// Get the widget type from its integral representation
fn from_i32(val: i32) -> Self;
}
/// Defines the methods implemented by all widgets
pub unsafe trait WidgetExt {
/// Set to position x, y
fn set_pos(&mut self, x: i32, y: i32);
/// Set to dimensions width and height
fn set_size(&mut self, width: i32, height: i32);
/// Sets the widget's label.
/// labels support special symbols preceded by an `@` [sign](https://www.fltk.org/doc-1.3/symbols.png).
/// and for the [associated formatting](https://www.fltk.org/doc-1.3/common.html).
fn set_label(&mut self, title: &str);
/// Redraws a widget, necessary for resizing and changing positions
fn redraw(&mut self);
/// Shows the widget
fn show(&mut self);
/// Hides the widget
fn hide(&mut self);
/// Returns the x coordinate of the widget
fn x(&self) -> i32;
/// Returns the y coordinate of the widget
fn y(&self) -> i32;
/// Returns the width of the widget
fn width(&self) -> i32;
/// Returns the height of the widget
fn height(&self) -> i32;
/// Returns the width of the widget
fn w(&self) -> i32;
/// Returns the height of the widget
fn h(&self) -> i32;
/// Returns the label of the widget
fn label(&self) -> String;
/// Measures the label's width and height
fn measure_label(&self) -> (i32, i32);
/// transforms a widget to a base `Fl_Widget`, for internal use
/// # Safety
/// Can return multiple mutable pointers to the same widget
unsafe fn as_widget_ptr(&self) -> *mut fltk_sys::widget::Fl_Widget;
/// Initialize to position x, y, (should only be called on initialization)
fn with_pos(self, x: i32, y: i32) -> Self
where
Self: Sized;
/// Initialilze to dimensions width and height, (should only be called on initialization)
fn with_size(self, width: i32, height: i32) -> Self
where
Self: Sized;
/// Initialize with label/title, (should only be called on initialization)
fn with_label(self, title: &str) -> Self
where
Self: Sized;
/// Sets the initial alignment of the widget, (should only be called on initialization)
fn with_align(self, align: Align) -> Self
where
Self: Sized;
/// Positions the widget below w, the size of w should be known
fn below_of<W: WidgetExt>(self, w: &W, padding: i32) -> Self
where
Self: Sized;
/// Positions the widget above w, the size of w should be known
fn above_of<W: WidgetExt>(self, w: &W, padding: i32) -> Self
where
Self: Sized;
/// Positions the widget to the right of w, the size of w should be known
fn right_of<W: WidgetExt>(self, w: &W, padding: i32) -> Self
where
Self: Sized;
/// Positions the widget to the left of w, the size of w should be known
fn left_of<W: WidgetExt>(self, w: &W, padding: i32) -> Self
where
Self: Sized;
/// Positions the widget to the center of w, the size of w should be known
fn center_of<W: WidgetExt>(self, w: &W) -> Self
where
Self: Sized;
/// Positions the widget to the center of its parent
fn center_of_parent(self) -> Self
where
Self: Sized;
/// Takes the size of w, the size of w should be known
fn size_of<W: WidgetExt>(self, w: &W) -> Self
where
Self: Sized;
/// Takes the size of the parent group or window
fn size_of_parent(self) -> Self
where
Self: Sized;
/// Checks whether the self widget is inside another widget
fn inside<W: WidgetExt>(&self, wid: &W) -> bool
where
Self: Sized;
/// Returns the widget type when applicable
fn get_type<T: WidgetType>(&self) -> T
where
Self: Sized;
/// Sets the widget type
fn set_type<T: WidgetType>(&mut self, typ: T)
where
Self: Sized;
/// Sets the image of the widget
fn set_image<I: ImageExt>(&mut self, image: Option<I>)
where
Self: Sized;
/// Gets the image associated with the widget
fn image(&self) -> Option<Box<dyn ImageExt>>
where
Self: Sized;
/// Sets the image of the widget
fn set_deimage<I: ImageExt>(&mut self, image: Option<I>)
where
Self: Sized;
/// Gets the image associated with the widget
fn deimage(&self) -> Option<Box<dyn ImageExt>>
where
Self: Sized;
/// Sets the callback when the widget is triggered (clicks for example)
/// takes the widget as a closure argument
fn set_callback<F: FnMut(&mut Self) + 'static>(&mut self, cb: F)
where
Self: Sized;
/// Emits a message on callback using a sender
fn emit<T: 'static + Clone + Send + Sync>(&mut self, sender: crate::app::Sender<T>, msg: T)
where
Self: Sized;
/// Activates the widget
fn activate(&mut self);
/// Deactivates the widget
fn deactivate(&mut self);
/// Redraws the label of the widget
fn redraw_label(&mut self);
/// Resizes and/or moves the widget, takes x, y, width and height
fn resize(&mut self, x: i32, y: i32, width: i32, height: i32);
/// Returns the tooltip text
fn tooltip(&self) -> Option<String>;
/// Sets the tooltip text
fn set_tooltip(&mut self, txt: &str);
/// Returns the widget color
fn color(&self) -> Color;
/// Sets the widget's color
fn set_color(&mut self, color: Color);
/// Returns the widget label's color
fn label_color(&self) -> Color;
/// Sets the widget label's color
fn set_label_color(&mut self, color: Color);
/// Returns the widget label's font
fn label_font(&self) -> Font;
/// Sets the widget label's font
fn set_label_font(&mut self, font: Font);
/// Returns the widget label's size
fn label_size(&self) -> i32;
/// Sets the widget label's size
fn set_label_size(&mut self, sz: i32);
/// Returns the widget label's type
fn label_type(&self) -> LabelType;
/// Sets the widget label's type
fn set_label_type(&mut self, typ: LabelType);
/// Returns the widget's frame type
fn frame(&self) -> FrameType;
/// Sets the widget's frame type
fn set_frame(&mut self, typ: FrameType);
/// Returns whether the widget was changed
fn changed(&self) -> bool;
/// Mark the widget as changed
fn set_changed(&mut self);
/// Clears the changed status of the widget
fn clear_changed(&mut self);
/// Returns the alignment of the widget
fn align(&self) -> Align;
/// Sets the alignment of the widget
fn set_align(&mut self, align: Align);
/// Returns the parent of the widget
fn parent(&self) -> Option<Box<dyn GroupExt>>;
/// Gets the selection color of the widget
fn selection_color(&mut self) -> Color;
/// Sets the selection color of the widget
fn set_selection_color(&mut self, color: Color);
/// Runs the already registered callback
fn do_callback(&mut self);
/// Returns the direct window holding the widget
fn window(&self) -> Option<Box<dyn WindowExt>>;
/// Returns the topmost window holding the widget
fn top_window(&self) -> Option<Box<dyn WindowExt>>;
/// Checks whether a widget is capable of taking events
fn takes_events(&self) -> bool;
/// Make the widget take focus
/// # Errors
/// Errors on failure to take focus
fn take_focus(&mut self) -> Result<(), FltkError>;
/// Set the widget to have visible focus
fn set_visible_focus(&mut self);
/// Clear visible focus
fn clear_visible_focus(&mut self);
/// Set the visible focus using a flag
fn visible_focus(&mut self, v: bool);
/// Return whether the widget has visible focus
fn has_visible_focus(&mut self) -> bool;
/// Check if a widget was deleted
fn was_deleted(&self) -> bool;
/// Return whether the widget was damaged
fn damage(&self) -> bool;
/// Signal the widget as damaged and it should be redrawn in the next event loop cycle
fn set_damage(&mut self, flag: bool);
/// Return the damage mask
fn damage_type(&self) -> Damage;
/// Signal the type of damage a widget received
fn set_damage_type(&mut self, mask: Damage);
/// Clear the damaged flag
fn clear_damage(&mut self);
/// Sets the default callback trigger for a widget
fn set_trigger(&mut self, trigger: CallbackTrigger);
/// Return the callback trigger
fn trigger(&self) -> CallbackTrigger;
/// Return the widget as a window if it's a window
fn as_window(&self) -> Option<Box<dyn WindowExt>>;
/// Return the widget as a group widget if it's a group widget
fn as_group(&self) -> Option<Box<dyn GroupExt>>;
/// INTERNAL: Retakes ownership of the user callback data
/// # Safety
/// Can return multiple mutable references to the `user_data`
unsafe fn user_data(&self) -> Option<Box<dyn FnMut()>>;
/// Upcast a `WidgetExt` to a Widget
/// # Safety
/// Allows for potentially unsafe casts between incompatible widget types
unsafe fn into_widget<W: WidgetBase>(&self) -> W
where
Self: Sized;
/// Returns whether a widget is visible
fn visible(&self) -> bool;
/// Returns whether a widget or any of its parents are visible (recursively)
fn visible_r(&self) -> bool;
}
/// Defines the extended methods implemented by all widgets
pub unsafe trait WidgetBase: WidgetExt {
/// Creates a new widget, takes an x, y coordinates, as well as a width and height, plus a title
/// # Arguments
/// * `x` - The x coordinate in the screen
/// * `y` - The y coordinate in the screen
/// * `width` - The width of the widget
/// * `heigth` - The height of the widget
/// * `title` - The title or label of the widget
/// The title is expected to be a static str or None.
/// To use dynamic strings use `with_label(self, &str)` or `set_label(&mut self, &str)`
/// labels support special symbols preceded by an `@` [sign](https://www.fltk.org/doc-1.3/symbols.png).
/// and for the [associated formatting](https://www.fltk.org/doc-1.3/common.html).
fn new<T: Into<Option<&'static str>>>(
x: i32,
y: i32,
width: i32,
height: i32,
title: T,
) -> Self;
/// Deletes widgets and their children.
fn delete(wid: Self)
where
Self: Sized;
/// transforms a widget pointer to a Widget, for internal use
/// # Safety
/// The pointer must be valid
unsafe fn from_widget_ptr(ptr: *mut fltk_sys::widget::Fl_Widget) -> Self;
/// Get a widget from base widget
/// # Safety
/// The underlying object must be valid
unsafe fn from_widget<W: WidgetExt>(w: W) -> Self;
/// Set a custom handler, where events are managed manually, akin to `Fl_Widget::handle(int)`.
/// Handled or ignored events should return true, unhandled events should return false.
/// takes the widget as a closure argument
fn handle<F: FnMut(&mut Self, Event) -> bool + 'static>(&mut self, cb: F);
/// Set a custom draw method.
/// takes the widget as a closure argument.
/// macOS requires that `WidgetBase::draw` actually calls drawing functions
fn draw<F: FnMut(&mut Self) + 'static>(&mut self, cb: F);
/// INTERNAL: Retrieve the draw data
/// # Safety
/// Can return multiple mutable references to the `draw_data`
unsafe fn draw_data(&mut self) -> Option<Box<dyn FnMut()>>;
/// INTERNAL: Retrieve the handle data
/// # Safety
/// Can return multiple mutable references to the `handle_data`
unsafe fn handle_data(&mut self) -> Option<Box<dyn FnMut(Event) -> bool>>;
}
/// Defines the methods implemented by all button widgets
pub unsafe trait ButtonExt: WidgetExt {
/// Gets the shortcut associated with a button
fn shortcut(&self) -> Shortcut;
/// Sets the shortcut associated with a button
fn set_shortcut(&mut self, shortcut: Shortcut);
/// Clears the value of the button.
/// Useful for round, radio, light, toggle and check buttons
fn clear(&mut self);
/// Returns whether a button is set or not.
/// Useful for round, radio, light, toggle and check buttons
fn is_set(&self) -> bool;
/// Sets whether a button is set or not.
/// Useful for round, radio, light, toggle and check buttons
fn set(&mut self, flag: bool);
/// Returns whether a button is set or not.
/// Useful for round, radio, light, toggle and check buttons
fn value(&self) -> bool;
/// Sets whether a button is set or not.
/// Useful for round, radio, light, toggle and check buttons
fn set_value(&mut self, flag: bool);
/// Set the `down_box` of the widget
fn set_down_frame(&mut self, f: FrameType);
/// Get the down frame type of the widget
fn down_frame(&self) -> FrameType;
}
/// Defines the methods implemented by all group widgets
pub unsafe trait GroupExt: WidgetExt {
/// Begins a group, used for widgets implementing the group trait
fn begin(&self);
/// Ends a group, used for widgets implementing the group trait
fn end(&self);
/// Clear a group from all widgets
fn clear(&mut self);
/// Clear a group from all widgets using FLTK's clear call.
/// # Safety
/// Ignores widget tracking
unsafe fn unsafe_clear(&mut self);
/// Return the number of children in a group
fn children(&self) -> i32;
/// Return child widget by index
fn child(&self, idx: i32) -> Option<Box<dyn WidgetExt>>;
/// Find a widget within a group and return its index
fn find<W: WidgetExt>(&self, widget: &W) -> i32
where
Self: Sized;
/// Add a widget to a group
fn add<W: WidgetExt>(&mut self, widget: &W)
where
Self: Sized;
/// Insert a widget to a group at a certain index
fn insert<W: WidgetExt>(&mut self, widget: &W, index: i32)
where
Self: Sized;
/// Remove a widget from a group, but does not delete it
fn remove<W: WidgetExt>(&mut self, widget: &W)
where
Self: Sized;
/// Remove a child widget by its index
fn remove_by_index(&mut self, idx: i32);
/// The resizable widget defines both the resizing frame and the resizing behavior of the group and its children.
fn resizable<W: WidgetExt>(&self, widget: &W)
where
Self: Sized;
/// Make the group itself resizable, should be called before the widget is shown
fn make_resizable(&mut self, val: bool);
/// Adds a widget to the group and makes it the resizable widget
fn add_resizable<W: WidgetExt>(&mut self, widget: &W)
where
Self: Sized;
/// Clips children outside the group boundaries
fn set_clip_children(&mut self, flag: bool);
/// Get whether `clip_children` is set
fn clip_children(&mut self) -> bool;
/// Draw a child widget, the call should be in a `WidgetBase::draw` method
fn draw_child<W: WidgetExt>(&self, w: &mut W)
where
Self: Sized;
/// Update a child widget, the call should be in a `WidgetBase::draw` method
fn update_child<W: WidgetExt>(&self, w: &mut W)
where
Self: Sized;
/// Draw the outside label, the call should be in a `WidgetBase::draw` method
fn draw_outside_label<W: WidgetExt>(&self, w: &mut W)
where
Self: Sized;
/// Draw children, the call should be in a `WidgetBase::draw` method
fn draw_children(&mut self);
/// Resets the internal array of widget sizes and positions
fn init_sizes(&mut self);
/// Get the bounds of all children widgets (left, upper, right, bottom)
fn bounds(&self) -> Vec<(i32, i32, i32, i32)>;
}
/// Defines the methods implemented by all window widgets
pub unsafe trait WindowExt: GroupExt {
/// Positions the window to the center of the screen
fn center_screen(self) -> Self
where
Self: Sized;
/// Makes a window modal, should be called before `show`
fn make_modal(&mut self, val: bool);
/// Makes a window fullscreen
fn fullscreen(&mut self, val: bool);
/// Makes the window current
fn make_current(&mut self);
/// Returns the icon of the window
fn icon(&self) -> Option<Box<dyn ImageExt>>;
/// Sets the windows icon.
/// Supported formats are bmp, jpeg, png and rgb.
fn set_icon<T: ImageExt>(&mut self, image: Option<T>)
where
Self: Sized;
/// Sets the cursor style within the window.
/// Needs to be called after the window is shown
fn set_cursor(&mut self, cursor: Cursor);
/// Returns whether a window is shown
fn shown(&self) -> bool;
/// Sets whether the window has a border
fn set_border(&mut self, flag: bool);
/// Returns whether a window has a border
fn border(&self) -> bool;
/// Frees the position of the window
fn free_position(&mut self);
/// Get the raw system handle of the window
fn raw_handle(&self) -> crate::window::RawHandle;
/// Set the window associated with a raw handle.
/// `RawHandle` is a void pointer to: (Windows: `HWND`, X11: `Xid` (`u64`), macOS: `NSWindow`)
/// # Safety
/// The data must be valid and is OS-dependent. The window must be shown.
unsafe fn set_raw_handle(&mut self, handle: crate::window::RawHandle);
/// Get the graphical draw region of the window
fn region(&self) -> crate::draw::Region;
/// Set the graphical draw region of the window
/// # Safety
/// The data must be valid.
unsafe fn set_region(&mut self, region: crate::draw::Region);
/// Iconifies the window.
/// You can tell that the window is iconized by checking that it's shown and not visible
fn iconize(&mut self);
/// Returns whether the window is fullscreen or not
fn fullscreen_active(&self) -> bool;
/// Returns the decorated width
fn decorated_w(&self) -> i32;
/// Returns the decorated height
fn decorated_h(&self) -> i32;
/// Set the window's minimum width, minimum height, max width and max height
fn size_range(&mut self, min_w: i32, min_h: i32, max_w: i32, max_h: i32);
/// Set the hotspot widget of the window
fn hotspot<W: WidgetExt>(&mut self, w: &W)
where
Self: Sized;
/// Set the shape of the window.
/// Supported image formats are BMP, RGB and Pixmap.
/// The window covers non-transparent/non-black shape of the image.
/// The image must not be scaled(resized) beforehand.
/// The size will be adapted to the window's size
fn set_shape<I: ImageExt>(&mut self, image: Option<I>)
where
Self: Sized;
/// Get the shape of the window
fn shape(&self) -> Option<Box<dyn ImageExt>>;
/// Get the window's x coord from the screen
fn x_root(&self) -> i32;
/// Get the window's y coord from the screen
fn y_root(&self) -> i32;
/// Set the cursor image
fn set_cursor_image(&mut self, image: crate::image::RgbImage, hot_x: i32, hot_y: i32);
/// Set the window's default cursor
fn default_cursor(&mut self, cursor: Cursor);
/// Get the screen number
fn screen_num(&self) -> i32;
/// Set the screen number
fn set_screen_num(&mut self, n: i32);
}
/// Defines the methods implemented by all input and output widgets
pub unsafe trait InputExt: WidgetExt {
/// Returns the value inside the input/output widget
fn value(&self) -> String;
/// Sets the value inside an input/output widget
fn set_value(&mut self, val: &str);
/// Returns the maximum size (in bytes) accepted by an input/output widget
fn maximum_size(&self) -> i32;
/// Sets the maximum size (in bytes) accepted by an input/output widget
fn set_maximum_size(&mut self, val: i32);
/// Returns the index position inside an input/output widget
fn position(&self) -> i32;
/// Sets the index postion inside an input/output widget
/// # Errors
/// Errors on failure to set the cursor position in the text
fn set_position(&mut self, val: i32) -> Result<(), FltkError>;
/// Returns the index mark inside an input/output widget
fn mark(&self) -> i32;
/// Sets the index mark inside an input/output widget
/// # Errors
/// Errors on failure to set the mark
fn set_mark(&mut self, val: i32) -> Result<(), FltkError>;
/// Replace content with a &str
/// # Errors
/// Errors on failure to replace text
fn replace(&mut self, beg: i32, end: i32, val: &str) -> Result<(), FltkError>;
/// Insert a &str
/// # Errors
/// Errors on failure to insert text
fn insert(&mut self, txt: &str) -> Result<(), FltkError>;
/// Append a &str
/// # Errors
/// Errors on failure to append text
fn append(&mut self, txt: &str) -> Result<(), FltkError>;
/// Copy the value within the widget
/// # Errors
/// Errors on failure to copy selection
fn copy(&mut self) -> Result<(), FltkError>;
/// Undo changes
/// # Errors
/// Errors on failure to undo
fn undo(&mut self) -> Result<(), FltkError>;
/// Cut the value within the widget
/// # Errors
/// Errors on failure to cut selection
fn cut(&mut self) -> Result<(), FltkError>;
/// Return the text font
fn text_font(&self) -> Font;
/// Sets the text font
fn set_text_font(&mut self, font: Font);
/// Return the text color
fn text_color(&self) -> Color;
/// Sets the text color
fn set_text_color(&mut self, color: Color);
/// Return the text size
fn text_size(&self) -> i32;
/// Sets the text size
fn set_text_size(&mut self, sz: i32);
/// Returns whether the input/output widget is readonly
fn readonly(&self) -> bool;
/// Set readonly status of the input/output widget
fn set_readonly(&mut self, val: bool);
/// Return whether text is wrapped inside an input/output widget
fn wrap(&self) -> bool;
/// Set whether text is wrapped inside an input/output widget
fn set_wrap(&mut self, val: bool);
}
/// Defines the methods implemented by all menu widgets
pub unsafe trait MenuExt: WidgetExt {
/// Get a menu item by name
fn find_item(&self, name: &str) -> Option<crate::menu::MenuItem>;
/// Set selected item
fn set_item(&mut self, item: &crate::menu::MenuItem) -> bool;
/// Find an item's index by its label
fn find_index(&self, label: &str) -> i32;
/// Return the text font
fn text_font(&self) -> Font;
/// Sets the text font
fn set_text_font(&mut self, c: Font);
/// Return the text size
fn text_size(&self) -> i32;
/// Sets the text size
fn set_text_size(&mut self, c: i32);
/// Return the text color
fn text_color(&self) -> Color;
/// Sets the text color
fn set_text_color(&mut self, c: Color);
/// Add a menu item along with its callback.
/// The characters "&", "/", "\\", and "\_" (underscore) are treated as special characters in the label string. The "&" character specifies that the following character is an accelerator and will be underlined.
/// The "\\" character is used to escape the next character in the string. Labels starting with the "\_" (underscore) character cause a divider to be placed after that menu item.
/// Takes the menu item as a closure argument
fn add<F: FnMut(&mut Self) + 'static>(
&mut self,
name: &str,
shortcut: Shortcut,
flag: crate::menu::MenuFlag,
cb: F,
) where
Self: Sized;
/// Inserts a menu item at an index along with its callback.
/// The characters "&", "/", "\\", and "\_" (underscore) are treated as special characters in the label string. The "&" character specifies that the following character is an accelerator and will be underlined.
/// The "\\" character is used to escape the next character in the string. Labels starting with the "\_" (underscore) character cause a divider to be placed after that menu item.
/// Takes the menu item as a closure argument
fn insert<F: FnMut(&mut Self) + 'static>(
&mut self,
idx: i32,
name: &str,
shortcut: Shortcut,
flag: crate::menu::MenuFlag,
cb: F,
) where
Self: Sized;
/// Add a menu item along with an emit (sender and message).
/// The characters "&", "/", "\\", and "\_" (underscore) are treated as special characters in the label string. The "&" character specifies that the following character is an accelerator and will be underlined.
/// The "\\" character is used to escape the next character in the string. Labels starting with the "\_" (underscore) character cause a divider to be placed after that menu item.
fn add_emit<T: 'static + Clone + Send + Sync>(
&mut self,
label: &str,
shortcut: Shortcut,
flag: crate::menu::MenuFlag,
sender: crate::app::Sender<T>,
msg: T,
) where
Self: Sized;
/// Inserts a menu item along with an emit (sender and message).
/// The characters "&", "/", "\\", and "\_" (underscore) are treated as special characters in the label string. The "&" character specifies that the following character is an accelerator and will be underlined.
/// The "\\" character is used to escape the next character in the string. Labels starting with the "\_" (underscore) character cause a divider to be placed after that menu item.
fn insert_emit<T: 'static + Clone + Send + Sync>(
&mut self,
idx: i32,
label: &str,
shortcut: Shortcut,
flag: crate::menu::MenuFlag,
sender: crate::app::Sender<T>,
msg: T,
) where
Self: Sized;
/// Remove a menu item by index
fn remove(&mut self, idx: i32);
/// Adds a simple text option to the Choice and `MenuButton` widgets.
/// The characters "&", "/", "\\", "|", and "\_" (underscore) are treated as special characters in the label string. The "&" character specifies that the following character is an accelerator and will be underlined.
/// The "\\" character is used to escape the next character in the string. Labels starting with the "\_" (underscore) character cause a divider to be placed after that menu item.
fn add_choice(&mut self, text: &str);
/// Gets the user choice from the Choice and `MenuButton` widgets
fn choice(&self) -> Option<String>;
/// Get index into menu of the last item chosen, returns -1 if no item was chosen
fn value(&self) -> i32;
/// Set index into menu of the last item chosen,return true if the new value is different than the old one
fn set_value(&mut self, v: i32) -> bool;
/// Clears the items in a menu, effectively deleting them.
fn clear(&mut self);
/// Clears a submenu by index, failure return `FltkErrorKind::FailedOperation`
/// # Errors
/// Errors on failure to clear the submenu
fn clear_submenu(&mut self, idx: i32) -> Result<(), FltkError>;
/// Clears the items in a menu, effectively deleting them, and recursively force-cleans capturing callbacks
/// # Safety
/// Deletes `user_data` and any captured objects in the callback
unsafe fn unsafe_clear(&mut self);
/// Clears a submenu by index, failure return `FltkErrorKind::FailedOperation`. Also recursively force-cleans capturing callbacks
/// # Safety
/// Deletes `user_data` and any captured objects in the callback
/// # Errors
/// Errors on failure to clear the submenu
unsafe fn unsafe_clear_submenu(&mut self, idx: i32) -> Result<(), FltkError>;
/// Get the size of the menu widget
fn size(&self) -> i32;
/// Get the text label of the menu item at index idx
fn text(&self, idx: i32) -> Option<String>;
/// Get the menu item at an index
fn at(&self, idx: i32) -> Option<crate::menu::MenuItem>;
/// Set the mode of a menu item by index and flag
fn mode(&self, idx: i32) -> crate::menu::MenuFlag;
/// Get the mode of a menu item
fn set_mode(&mut self, idx: i32, flag: crate::menu::MenuFlag);
/// End the menu
fn end(&mut self);
/// Set the `down_box` of the widget
fn set_down_frame(&mut self, f: FrameType);
/// Get the down frame type of the widget
fn down_frame(&self) -> FrameType;
/// Make a menu globally accessible from any window
fn global(&mut self);
}
/// Defines the methods implemented by all valuator widgets
pub unsafe trait ValuatorExt: WidgetExt {
/// Set bounds of a valuator
fn set_bounds(&mut self, a: f64, b: f64);
/// Get the minimum bound of a valuator
fn minimum(&self) -> f64;
/// Set the minimum bound of a valuator
fn set_minimum(&mut self, a: f64);
/// Get the maximum bound of a valuator
fn maximum(&self) -> f64;
/// Set the maximum bound of a valuator
fn set_maximum(&mut self, a: f64);
/// Set the range of a valuator
fn set_range(&mut self, a: f64, b: f64);
/// Set change step of a valuator.
/// Rounds to multiples of a/b, or no rounding if a is zero
fn set_step(&mut self, a: f64, b: i32);
/// Get change step of a valuator
fn step(&self) -> f64;
/// Set the precision of a valuator
fn set_precision(&mut self, digits: i32);
/// Get the value of a valuator
fn value(&self) -> f64;
/// Set the value of a valuator
fn set_value(&mut self, arg2: f64);
/// Set the format of a valuator
/// # Errors
/// Errors on failure to set the format of the widget
fn format(&mut self, arg2: &str) -> Result<(), FltkError>;
/// Round the valuator
fn round(&self, arg2: f64) -> f64;
/// Clamp the valuator
fn clamp(&self, arg2: f64) -> f64;
/// Increment the valuator
fn increment(&mut self, arg2: f64, arg3: i32) -> f64;
}
/// Defines the methods implemented by `TextDisplay` and `TextEditor`
pub unsafe trait DisplayExt: WidgetExt {
/// Get the associated `TextBuffer`
fn buffer(&self) -> Option<crate::text::TextBuffer>;
/// Sets the associated `TextBuffer`
fn set_buffer<B: Into<Option<crate::text::TextBuffer>>>(&mut self, buffer: B);
/// Get the associated style `TextBuffer`
fn style_buffer(&self) -> Option<crate::text::TextBuffer>;
/// Return the text font
fn text_font(&self) -> Font;
/// Sets the text font
fn set_text_font(&mut self, font: Font);
/// Return the text color
fn text_color(&self) -> Color;
/// Sets the text color
fn set_text_color(&mut self, color: Color);
/// Return the text size
fn text_size(&self) -> i32;
/// Sets the text size
fn set_text_size(&mut self, sz: i32);
/// Scroll down the Display widget
fn scroll(&mut self, top_line_num: i32, horiz_offset: i32);
/// Insert into Display widget
fn insert(&self, text: &str);
/// Set the insert position
fn set_insert_position(&mut self, new_pos: i32);
/// Return the insert position
fn insert_position(&self) -> i32;
/// Gets the x and y positions of the cursor
fn position_to_xy(&self, pos: i32) -> (i32, i32);
/// Counts the lines from start to end
fn count_lines(&self, start: i32, end: i32, is_line_start: bool) -> i32;
/// Moves the cursor right
/// # Errors
/// Errors on failure to move the cursor
fn move_right(&mut self) -> Result<(), FltkError>;
/// Moves the cursor left
/// # Errors
/// Errors on failure to move the cursor
fn move_left(&mut self) -> Result<(), FltkError>;
/// Moves the cursor up
/// # Errors
/// Errors on failure to move the cursor
fn move_up(&mut self) -> Result<(), FltkError>;
/// Moves the cursor down
/// # Errors
/// Errors on failure to move the cursor
fn move_down(&mut self) -> Result<(), FltkError>;
/// Shows/hides the cursor
fn show_cursor(&mut self, val: bool);
/// Sets the style of the text widget
fn set_highlight_data<B: Into<Option<crate::text::TextBuffer>>>(
&mut self,
style_buffer: B,
entries: Vec<crate::text::StyleTableEntry>,
);
/// Sets the cursor style
fn set_cursor_style(&mut self, style: crate::text::Cursor);
/// Sets the cursor color
fn set_cursor_color(&mut self, color: Color);
/// Sets the scrollbar size in pixels
fn set_scrollbar_size(&mut self, size: i32);
/// Sets the scrollbar alignment
fn set_scrollbar_align(&mut self, align: Align);
/// Returns the cursor style
fn cursor_style(&self) -> crate::text::Cursor;
/// Returns the cursor color
fn cursor_color(&self) -> Color;
/// Returns the scrollbar size in pixels
fn scrollbar_size(&self) -> i32;
/// Returns the scrollbar alignment
fn scrollbar_align(&self) -> Align;
/// Returns the beginning of the line from the current position.
/// Returns new position as index
fn line_start(&self, pos: i32) -> i32;
/// Returns the ending of the line from the current position.
/// Returns new position as index
fn line_end(&self, start_pos: i32, is_line_start: bool) -> i32;
/// Skips lines from `start_pos`
fn skip_lines(&mut self, start_pos: i32, lines: i32, is_line_start: bool) -> i32;
/// Rewinds the lines
fn rewind_lines(&mut self, start_pos: i32, lines: i32) -> i32;
/// Goes to the next word
fn next_word(&mut self);
/// Goes to the previous word
fn previous_word(&mut self);
/// Returns the position of the start of the word, relative to the current position
fn word_start(&self, pos: i32) -> i32;
/// Returns the position of the end of the word, relative to the current position
fn word_end(&self, pos: i32) -> i32;
/// Convert an x pixel position into a column number.
fn x_to_col(&self, x: f64) -> f64;
/// Convert a column number into an x pixel position
fn col_to_x(&self, col: f64) -> f64;
/// Sets the linenumber width
fn set_linenumber_width(&mut self, w: i32);
/// Gets the linenumber width
fn linenumber_width(&self) -> i32;
/// Sets the linenumber font
fn set_linenumber_font(&mut self, font: Font);
/// Gets the linenumber font
fn linenumber_font(&self) -> Font;
/// Sets the linenumber size
fn set_linenumber_size(&mut self, size: i32);
/// Gets the linenumber size
fn linenumber_size(&self) -> i32;
/// Sets the linenumber foreground color
fn set_linenumber_fgcolor(&mut self, color: Color);
/// Gets the linenumber foreground color
fn linenumber_fgcolor(&self) -> Color;
/// Sets the linenumber background color
fn set_linenumber_bgcolor(&mut self, color: Color);
/// Gets the linenumber background color
fn linenumber_bgcolor(&self) -> Color;
/// Sets the linenumber alignment
fn set_linenumber_align(&mut self, align: Align);
/// Gets the linenumber alignment
fn linenumber_align(&self) -> Align;
/// Checks whether a pixel is within a text selection
fn in_selection(&self, x: i32, y: i32) -> bool;
/// Sets the wrap mode of the Display widget.
/// If the wrap mode is `AtColumn`, wrap margin is the column.
/// If the wrap mode is `AtPixel`, wrap margin is the pixel.
/// For more [info](https://www.fltk.org/doc-1.4/classFl__Text__Display.html#ab9378d48b949f8fc7da04c6be4142c54)
fn wrap_mode(&mut self, wrap: crate::text::WrapMode, wrap_margin: i32);
/// Correct a column number based on an unconstrained position
fn wrapped_column(&self, row: i32, column: i32) -> i32;
/// Correct a row number from an unconstrained position
fn wrapped_row(&self, row: i32) -> i32;
}
/// Defines the methods implemented by all browser types
pub unsafe trait BrowserExt: WidgetExt {
/// Removes the specified line.
/// Lines start at 1
fn remove(&mut self, line: i32);
/// Adds an item
fn add(&mut self, item: &str);
/// Inserts an item at an index.
/// Lines start at 1
fn insert(&mut self, line: i32, item: &str);
/// Moves an item.
/// Lines start at 1
fn move_item(&mut self, to: i32, from: i32);
/// Swaps 2 items.
/// Lines start at 1
fn swap(&mut self, a: i32, b: i32);
/// Clears the browser widget
fn clear(&mut self);
/// Returns the number of items
fn size(&self) -> i32;
/// Select an item at the specified line.
/// Lines start at 1
fn select(&mut self, line: i32);
/// Returns whether the item is selected
/// Lines start at 1
fn selected(&self, line: i32) -> bool;
/// Returns the text of the item at `line`.
/// Lines start at 1
fn text(&self, line: i32) -> Option<String>;
/// Returns the text of the selected item.
/// Lines start at 1
fn selected_text(&self) -> Option<String>;
/// Sets the text of the selected item.
/// Lines start at 1
fn set_text(&mut self, line: i32, txt: &str);
/// Load a file
/// # Errors
/// Errors on non-existent paths
fn load<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<(), FltkError>;
/// Return the text size
fn text_size(&self) -> i32;
/// Sets the text size.
/// Lines start at 1
fn set_text_size(&mut self, sz: i32);
/// Sets the icon for browser elements.
/// Lines start at 1
fn set_icon<Img: ImageExt>(&mut self, line: i32, image: Option<Img>);
/// Returns the icon of a browser element.
/// Lines start at 1
fn icon(&self, line: i32) -> Option<Box<dyn ImageExt>>;
/// Removes the icon of a browser element.
/// Lines start at 1
fn remove_icon(&mut self, line: i32);
/// Scrolls the browser so the top item in the browser is showing the specified line.
/// Lines start at 1
fn top_line(&mut self, line: i32);
/// Scrolls the browser so the bottom item in the browser is showing the specified line.
/// Lines start at 1
fn bottom_line(&mut self, line: i32);
/// Scrolls the browser so the middle item in the browser is showing the specified line.
/// Lines start at 1
fn middle_line(&mut self, line: i32);
/// Gets the current format code prefix character, which by default is '\@'.
/// More info [here](https://www.fltk.org/doc-1.3/classFl__Browser.html#a129dca59d64baf166503ba59341add69)
fn format_char(&self) -> char;
/// Sets the current format code prefix character to \p c. The default prefix is '\@'.
/// c should be ascii
fn set_format_char(&mut self, c: char);
/// Gets the current column separator character. The default is '\t'
fn column_char(&self) -> char;
/// Sets the column separator to c. This will only have an effect if you also use `set_column_widths()`.
/// c should be ascii
fn set_column_char(&mut self, c: char);
/// Gets the current column width array
fn column_widths(&self) -> Vec<i32>;
/// Sets the current column width array
fn set_column_widths(&mut self, arr: &'static [i32]);
/// Returns whether a certain line is displayed
fn displayed(&self, line: i32) -> bool;
/// Makes a specified line visible
fn make_visible(&mut self, line: i32);
/// Gets the vertical scroll position of the list as a pixel position
fn position(&self) -> i32;
/// Sets the vertical scroll position of the list as a pixel position
fn set_position(&mut self, pos: i32);
/// Gets the horizontal scroll position of the list as a pixel position
fn hposition(&self) -> i32;
/// Sets the horizontal scroll position of the list as a pixel position
fn set_hposition(&mut self, pos: i32);
/// Returns the type of scrollbar associated with the browser
fn has_scrollbar(&self) -> crate::browser::BrowserScrollbar;
/// Sets the type of scrollbar associated with the browser
fn set_has_scrollbar(&mut self, mode: crate::browser::BrowserScrollbar);
/// Gets the scrollbar size
fn scrollbar_size(&self) -> i32;
/// Sets the scrollbar size
fn set_scrollbar_size(&mut self, new_size: i32);
/// Sorts the items of the browser
fn sort(&mut self);
/// Returns the vertical scrollbar
fn scrollbar(&self) -> Box<dyn ValuatorExt>;
/// Returns the horizontal scrollbar
fn hscrollbar(&self) -> Box<dyn ValuatorExt>;
/// Returns the selected line, returns 0 if no line is selected
fn value(&self) -> i32;
}
/// Defines the methods implemented by table types
pub unsafe trait TableExt: GroupExt {
/// Clears the table
fn clear(&mut self);
/// Sets the table frame
fn set_table_frame(&mut self, frame: FrameType);
/// Gets the table frame
fn table_frame(&self) -> FrameType;
/// Sets the number of rows
fn set_rows(&mut self, val: i32);
/// Gets the number of rows
fn rows(&self) -> i32;
/// Sets the number of columns
fn set_cols(&mut self, val: i32);
/// Gets the number of columns
fn cols(&self) -> i32;
/// The range of row and column numbers for all visible and partially visible cells in the table.
/// Returns (`row_top`, `col_left`, `row_bot`, `col_right`)
fn visible_cells(&self) -> (i32, i32, i32, i32);
/// Returns whether the resize is interactive
fn is_interactive_resize(&self) -> bool;
/// Returns whether a row is resizable
fn row_resize(&self) -> bool;
/// Sets a row to be resizable
fn set_row_resize(&mut self, flag: bool);
/// Returns whether a column is resizable
fn col_resize(&self) -> bool;
/// Sets a column to be resizable
fn set_col_resize(&mut self, flag: bool);
/// Returns the current column minimum resize value.
fn col_resize_min(&self) -> i32;
/// Sets the current column minimum resize value.
fn set_col_resize_min(&mut self, val: i32);
/// Returns the current row minimum resize value.
fn row_resize_min(&self) -> i32;
/// Sets the current row minimum resize value.
fn set_row_resize_min(&mut self, val: i32);
/// Returns if row headers are enabled or not
fn row_header(&self) -> bool;
/// Sets whether a row headers are enabled or not
fn set_row_header(&mut self, flag: bool);
/// Returns if column headers are enabled or not
fn col_header(&self) -> bool;
/// Sets whether a column headers are enabled or not
fn set_col_header(&mut self, flag: bool);
/// Sets the column header height
fn set_col_header_height(&mut self, height: i32);
/// Gets the column header height
fn col_header_height(&self) -> i32;
/// Sets the row header width
fn set_row_header_width(&mut self, width: i32);
/// Gets the row header width
fn row_header_width(&self) -> i32;
/// Sets the row header color
fn set_row_header_color(&mut self, val: Color);
/// Gets the row header color
fn row_header_color(&self) -> Color;
/// Sets the column header color
fn set_col_header_color(&mut self, val: Color);
/// Gets the row header color
fn col_header_color(&self) -> Color;
/// Sets the row's height
fn set_row_height(&mut self, row: i32, height: i32);
/// Gets the row's height
fn row_height(&self, row: i32) -> i32;
/// Sets the columns's width
fn set_col_width(&mut self, col: i32, width: i32);
/// Gets the columns's width
fn col_width(&self, col: i32) -> i32;
/// Sets all rows height
fn set_row_height_all(&mut self, height: i32);
/// Sets all columns's width
fn set_col_width_all(&mut self, width: i32);
/// Sets the row's position
fn set_row_position(&mut self, row: i32);
/// Sets the columns's position
fn set_col_position(&mut self, col: i32);
/// Gets the row's position
fn row_position(&self) -> i32;
/// Gets the columns's position
fn col_position(&self) -> i32;
/// Sets the top row
fn set_top_row(&mut self, row: i32);
/// Gets the top row
fn top_row(&self) -> i32;
/// Returns whether a cell is selected
fn is_selected(&self, r: i32, c: i32) -> bool;
/// Gets the selection.
/// Returns (`row_top`, `col_left`, `row_bot`, `col_right`)
fn get_selection(&self) -> (i32, i32, i32, i32);
/// Sets the selection
fn set_selection(&mut self, row_top: i32, col_left: i32, row_bot: i32, col_right: i32);
/// Unset selection
fn unset_selection(&mut self);
/// Moves the cursor with shift select
/// # Errors
/// Errors on failure to move the cursor
fn move_cursor_with_shift_select(
&mut self,
r: i32,
c: i32,
shiftselect: bool,
) -> Result<(), FltkError>;
/// Moves the cursor
/// # Errors
/// Errors on failure to move the cursor
fn move_cursor(&mut self, r: i32, c: i32) -> Result<(), FltkError>;
/// Returns the scrollbar size
fn scrollbar_size(&self) -> i32;
/// Sets the scrollbar size
fn set_scrollbar_size(&mut self, new_size: i32);
/// Sets whether tab key cell navigation is enabled
fn set_tab_cell_nav(&mut self, val: bool);
/// Returns whether tab key cell navigation is enabled
fn tab_cell_nav(&self) -> bool;
/// Override `draw_cell`.
/// callback args: &mut self, `TableContext`, Row: i32, Column: i32, X: i32, Y: i32, Width: i32 and Height: i32.
/// takes the widget as a closure argument
fn draw_cell<
F: FnMut(&mut Self, crate::table::TableContext, i32, i32, i32, i32, i32, i32) + 'static,
>(
&mut self,
cb: F,
);
/// INTERNAL: Retrieve the draw cell data
/// # Safety
/// Can return multiple mutable references to the `draw_cell_data`
unsafe fn draw_cell_data(&self) -> Option<Box<dyn FnMut()>>;
/// Get the callback column, should be called from within a callback
fn callback_col(&self) -> i32;
/// Get the callback row, should be called from within a callback
fn callback_row(&self) -> i32;
/// Get the callback context, should be called from within a callback
fn callback_context(&self) -> crate::table::TableContext;
}
/// Defines the methods implemented by all image types
pub unsafe trait ImageExt {
/// Performs a deep copy of the image
fn copy(&self) -> Self
where
Self: Sized;
/// Draws the image at the presupplied coordinates and size
fn draw(&mut self, x: i32, y: i32, width: i32, height: i32);
/// Return the width of the image
fn width(&self) -> i32;
/// Return the height of the image
fn height(&self) -> i32;
/// Return the width of the image
fn w(&self) -> i32;
/// Return the height of the image
fn h(&self) -> i32;
/// Retunrs a pointer of the image
/// # Safety
/// Can return multiple mutable pointers to the image
unsafe fn as_image_ptr(&self) -> *mut fltk_sys::image::Fl_Image;
/// Transforms a raw image pointer to an image
/// # Safety
/// The pointer must be valid
unsafe fn from_image_ptr(ptr: *mut fltk_sys::image::Fl_Image) -> Self
where
Self: Sized;
/// Returns the underlying raw rgb image data
fn to_rgb_data(&self) -> Vec<u8>;
/// Returns the underlying raw image data
fn to_raw_data(&self) -> *const *const u8;
/// Transforms the image into an `RgbImage`
/// # Errors
/// Errors on failure to transform to `RgbImage`
fn to_rgb(&self) -> Result<crate::image::RgbImage, FltkError>;
/// Scales the image
fn scale(&mut self, width: i32, height: i32, proportional: bool, can_expand: bool);
/// Return the count of an image
fn count(&self) -> i32;
/// Gets the image's data width
fn data_w(&self) -> i32;
/// Gets the image's data height
fn data_h(&self) -> i32;
/// Gets the image's depth
fn depth(&self) -> ColorDepth;
/// Gets the image's line data size
fn ld(&self) -> i32;
/// Greys the image
fn inactive(&mut self);
/// Deletes the image
/// # Safety
/// An image shouldn't be deleted while it's being used by a widget
unsafe fn delete(img: Self)
where
Self: Sized;
/// Checks if the image was deleted
fn was_deleted(&self) -> bool;
/// INTERNAL: Manually increment the atomic refcount
/// # Safety
/// The underlying image pointer must be valid
unsafe fn increment_arc(&mut self);
/// INTERNAL: Manually decrement the atomic refcount
/// # Safety
/// The underlying image pointer must be valid
unsafe fn decrement_arc(&mut self);
/// Transforms an Image base into another Image
/// # Safety
/// Can be unsafe if used to downcast to an image of different format
unsafe fn into_image<I: ImageExt>(self) -> I
where
Self: Sized;
}
/// Defines the methods implemented by all surface types, currently `ImageSurface`
pub trait SurfaceDevice {
/// Checks whether this surface is the current surface
fn is_current(&self) -> bool;
/// Get the current surface
fn surface() -> Self;
/// Push a surface as a current surface
fn push_current(new_current: &Self);
/// Pop the current surface
fn pop_current();
}
|
/*
* Datadog API V1 Collection
*
* Collection of all Datadog Public endpoints.
*
* The version of the OpenAPI document: 1.0
* Contact: support@datadoghq.com
* Generated by: https://openapi-generator.tech
*/
use reqwest;
use crate::apis::ResponseContent;
use super::{Error, configuration};
/// struct for typed errors of method `create_global_variable`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateGlobalVariableError {
Status400(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `create_private_location`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreatePrivateLocationError {
Status402(crate::models::ApiErrorResponse),
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `create_synthetics_api_test`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateSyntheticsApiTestError {
Status400(crate::models::ApiErrorResponse),
Status402(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `create_synthetics_browser_test`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateSyntheticsBrowserTestError {
Status400(crate::models::ApiErrorResponse),
Status402(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `delete_global_variable`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DeleteGlobalVariableError {
Status400(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `delete_private_location`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DeletePrivateLocationError {
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `delete_tests`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DeleteTestsError {
Status400(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `edit_global_variable`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum EditGlobalVariableError {
Status400(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `get_api_test`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetApiTestError {
Status403(crate::models::ApiErrorResponse),
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `get_api_test_latest_results`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetApiTestLatestResultsError {
Status403(crate::models::ApiErrorResponse),
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `get_api_test_result`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetApiTestResultError {
Status403(crate::models::ApiErrorResponse),
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `get_browser_test`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetBrowserTestError {
Status403(crate::models::ApiErrorResponse),
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `get_browser_test_latest_results`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetBrowserTestLatestResultsError {
Status403(crate::models::ApiErrorResponse),
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `get_browser_test_result`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetBrowserTestResultError {
Status403(crate::models::ApiErrorResponse),
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `get_global_variable`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetGlobalVariableError {
Status403(crate::models::ApiErrorResponse),
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `get_private_location`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetPrivateLocationError {
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `get_test`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetTestError {
Status403(crate::models::ApiErrorResponse),
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `list_locations`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ListLocationsError {
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `list_tests`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ListTestsError {
Status403(crate::models::ApiErrorResponse),
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `trigger_ci_tests`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum TriggerCiTestsError {
Status400(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `update_api_test`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdateApiTestError {
Status400(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `update_browser_test`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdateBrowserTestError {
Status400(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `update_private_location`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdatePrivateLocationError {
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// struct for typed errors of method `update_test_pause_status`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdateTestPauseStatusError {
Status400(crate::models::ApiErrorResponse),
Status403(crate::models::ApiErrorResponse),
Status404(crate::models::ApiErrorResponse),
UnknownValue(serde_json::Value),
}
/// Create a Synthetics global variable.
pub async fn create_global_variable(configuration: &configuration::Configuration, body: crate::models::SyntheticsGlobalVariable) -> Result<crate::models::SyntheticsGlobalVariable, Error<CreateGlobalVariableError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/variables", configuration.base_path);
let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
local_var_req_builder = local_var_req_builder.json(&body);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<CreateGlobalVariableError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Create a new Synthetics private location.
pub async fn create_private_location(configuration: &configuration::Configuration, body: crate::models::SyntheticsPrivateLocation) -> Result<crate::models::SyntheticsPrivateLocationCreationResponse, Error<CreatePrivateLocationError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/private-locations", configuration.base_path);
let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
local_var_req_builder = local_var_req_builder.json(&body);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<CreatePrivateLocationError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Create a Synthetic API test.
pub async fn create_synthetics_api_test(configuration: &configuration::Configuration, body: crate::models::SyntheticsApiTest) -> Result<crate::models::SyntheticsApiTest, Error<CreateSyntheticsApiTestError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/tests/api", configuration.base_path);
let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
local_var_req_builder = local_var_req_builder.json(&body);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<CreateSyntheticsApiTestError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Create a Synthetic browser test.
pub async fn create_synthetics_browser_test(configuration: &configuration::Configuration, body: crate::models::SyntheticsBrowserTest) -> Result<crate::models::SyntheticsBrowserTest, Error<CreateSyntheticsBrowserTestError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/tests/browser", configuration.base_path);
let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
local_var_req_builder = local_var_req_builder.json(&body);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<CreateSyntheticsBrowserTestError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Delete a Synthetics global variable.
pub async fn delete_global_variable(configuration: &configuration::Configuration, variable_id: &str) -> Result<(), Error<DeleteGlobalVariableError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/variables/{variable_id}", configuration.base_path, variable_id=crate::apis::urlencode(variable_id));
let mut local_var_req_builder = local_var_client.delete(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
Ok(())
} else {
let local_var_entity: Option<DeleteGlobalVariableError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Delete a Synthetics private location.
pub async fn delete_private_location(configuration: &configuration::Configuration, location_id: &str) -> Result<(), Error<DeletePrivateLocationError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/private-locations/{location_id}", configuration.base_path, location_id=crate::apis::urlencode(location_id));
let mut local_var_req_builder = local_var_client.delete(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
Ok(())
} else {
let local_var_entity: Option<DeletePrivateLocationError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Delete multiple Synthetic tests by ID.
pub async fn delete_tests(configuration: &configuration::Configuration, body: crate::models::SyntheticsDeleteTestsPayload) -> Result<crate::models::SyntheticsDeleteTestsResponse, Error<DeleteTestsError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/tests/delete", configuration.base_path);
let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
local_var_req_builder = local_var_req_builder.json(&body);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<DeleteTestsError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Edit a Synthetics global variable.
pub async fn edit_global_variable(configuration: &configuration::Configuration, variable_id: &str, body: crate::models::SyntheticsGlobalVariable) -> Result<crate::models::SyntheticsGlobalVariable, Error<EditGlobalVariableError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/variables/{variable_id}", configuration.base_path, variable_id=crate::apis::urlencode(variable_id));
let mut local_var_req_builder = local_var_client.put(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
local_var_req_builder = local_var_req_builder.json(&body);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<EditGlobalVariableError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Get the detailed configuration associated with a Synthetic API test.
pub async fn get_api_test(configuration: &configuration::Configuration, public_id: &str) -> Result<crate::models::SyntheticsApiTest, Error<GetApiTestError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/tests/api/{public_id}", configuration.base_path, public_id=crate::apis::urlencode(public_id));
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<GetApiTestError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Get the last 50 test results summaries for a given Synthetics API test.
pub async fn get_api_test_latest_results(configuration: &configuration::Configuration, public_id: &str, from_ts: Option<i64>, to_ts: Option<i64>, probe_dc: Option<Vec<String>>) -> Result<crate::models::SyntheticsGetApiTestLatestResultsResponse, Error<GetApiTestLatestResultsError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/tests/{public_id}/results", configuration.base_path, public_id=crate::apis::urlencode(public_id));
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
if let Some(ref local_var_str) = from_ts {
local_var_req_builder = local_var_req_builder.query(&[("from_ts", &local_var_str.to_string())]);
}
if let Some(ref local_var_str) = to_ts {
local_var_req_builder = local_var_req_builder.query(&[("to_ts", &local_var_str.to_string())]);
}
if let Some(ref local_var_str) = probe_dc {
local_var_req_builder = local_var_req_builder.query(&[("probe_dc", &local_var_str.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(",").to_string())]);
}
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<GetApiTestLatestResultsError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Get a specific full result from a given (API) Synthetic test.
pub async fn get_api_test_result(configuration: &configuration::Configuration, public_id: &str, result_id: &str) -> Result<crate::models::SyntheticsApiTestResultFull, Error<GetApiTestResultError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/tests/{public_id}/results/{result_id}", configuration.base_path, public_id=crate::apis::urlencode(public_id), result_id=crate::apis::urlencode(result_id));
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<GetApiTestResultError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Get the detailed configuration (including steps) associated with a Synthetic browser test.
pub async fn get_browser_test(configuration: &configuration::Configuration, public_id: &str) -> Result<crate::models::SyntheticsBrowserTest, Error<GetBrowserTestError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/tests/browser/{public_id}", configuration.base_path, public_id=crate::apis::urlencode(public_id));
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<GetBrowserTestError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Get the last 50 test results summaries for a given Synthetics Browser test.
pub async fn get_browser_test_latest_results(configuration: &configuration::Configuration, public_id: &str, from_ts: Option<i64>, to_ts: Option<i64>, probe_dc: Option<Vec<String>>) -> Result<crate::models::SyntheticsGetBrowserTestLatestResultsResponse, Error<GetBrowserTestLatestResultsError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/tests/browser/{public_id}/results", configuration.base_path, public_id=crate::apis::urlencode(public_id));
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
if let Some(ref local_var_str) = from_ts {
local_var_req_builder = local_var_req_builder.query(&[("from_ts", &local_var_str.to_string())]);
}
if let Some(ref local_var_str) = to_ts {
local_var_req_builder = local_var_req_builder.query(&[("to_ts", &local_var_str.to_string())]);
}
if let Some(ref local_var_str) = probe_dc {
local_var_req_builder = local_var_req_builder.query(&[("probe_dc", &local_var_str.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(",").to_string())]);
}
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<GetBrowserTestLatestResultsError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Get a specific full result from a given (browser) Synthetic test.
pub async fn get_browser_test_result(configuration: &configuration::Configuration, public_id: &str, result_id: &str) -> Result<crate::models::SyntheticsBrowserTestResultFull, Error<GetBrowserTestResultError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/tests/browser/{public_id}/results/{result_id}", configuration.base_path, public_id=crate::apis::urlencode(public_id), result_id=crate::apis::urlencode(result_id));
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<GetBrowserTestResultError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Get the detailed configuration of a global variable.
pub async fn get_global_variable(configuration: &configuration::Configuration, variable_id: &str) -> Result<crate::models::SyntheticsGlobalVariable, Error<GetGlobalVariableError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/variables/{variable_id}", configuration.base_path, variable_id=crate::apis::urlencode(variable_id));
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<GetGlobalVariableError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Get a Synthetics private location.
pub async fn get_private_location(configuration: &configuration::Configuration, location_id: &str) -> Result<crate::models::SyntheticsPrivateLocation, Error<GetPrivateLocationError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/private-locations/{location_id}", configuration.base_path, location_id=crate::apis::urlencode(location_id));
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<GetPrivateLocationError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Get the detailed configuration associated with a Synthetics test.
pub async fn get_test(configuration: &configuration::Configuration, public_id: &str) -> Result<crate::models::SyntheticsTestDetails, Error<GetTestError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/tests/{public_id}", configuration.base_path, public_id=crate::apis::urlencode(public_id));
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<GetTestError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Get the list of public and private locations available for Synthetic tests. No arguments required.
pub async fn list_locations(configuration: &configuration::Configuration, ) -> Result<crate::models::SyntheticsLocations, Error<ListLocationsError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/locations", configuration.base_path);
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<ListLocationsError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Get the list of all Synthetic tests.
pub async fn list_tests(configuration: &configuration::Configuration, ) -> Result<crate::models::SyntheticsListTestsResponse, Error<ListTestsError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/tests", configuration.base_path);
let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<ListTestsError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Trigger a set of Synthetics tests for continuous integration.
pub async fn trigger_ci_tests(configuration: &configuration::Configuration, body: crate::models::SyntheticsCiTestBody) -> Result<crate::models::SyntheticsTriggerCiTestsResponse, Error<TriggerCiTestsError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/tests/trigger/ci", configuration.base_path);
let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
local_var_req_builder = local_var_req_builder.json(&body);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<TriggerCiTestsError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Edit the configuration of a Synthetic API test.
pub async fn update_api_test(configuration: &configuration::Configuration, public_id: &str, body: crate::models::SyntheticsApiTest) -> Result<crate::models::SyntheticsApiTest, Error<UpdateApiTestError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/tests/api/{public_id}", configuration.base_path, public_id=crate::apis::urlencode(public_id));
let mut local_var_req_builder = local_var_client.put(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
local_var_req_builder = local_var_req_builder.json(&body);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<UpdateApiTestError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Edit the configuration of a Synthetic browser test.
pub async fn update_browser_test(configuration: &configuration::Configuration, public_id: &str, body: crate::models::SyntheticsBrowserTest) -> Result<crate::models::SyntheticsBrowserTest, Error<UpdateBrowserTestError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/tests/browser/{public_id}", configuration.base_path, public_id=crate::apis::urlencode(public_id));
let mut local_var_req_builder = local_var_client.put(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
local_var_req_builder = local_var_req_builder.json(&body);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<UpdateBrowserTestError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Edit a Synthetics private location.
pub async fn update_private_location(configuration: &configuration::Configuration, location_id: &str, body: crate::models::SyntheticsPrivateLocation) -> Result<crate::models::SyntheticsPrivateLocation, Error<UpdatePrivateLocationError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/private-locations/{location_id}", configuration.base_path, location_id=crate::apis::urlencode(location_id));
let mut local_var_req_builder = local_var_client.put(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
local_var_req_builder = local_var_req_builder.json(&body);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<UpdatePrivateLocationError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
/// Pause or start a Synthetics test by changing the status.
pub async fn update_test_pause_status(configuration: &configuration::Configuration, public_id: &str, body: crate::models::SyntheticsUpdateTestPauseStatusPayload) -> Result<bool, Error<UpdateTestPauseStatusError>> {
let local_var_client = &configuration.client;
let local_var_uri_str = format!("{}/api/v1/synthetics/tests/{public_id}/status", configuration.base_path, public_id=crate::apis::urlencode(public_id));
let mut local_var_req_builder = local_var_client.put(local_var_uri_str.as_str());
if let Some(ref local_var_user_agent) = configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value);
};
if let Some(ref local_var_apikey) = configuration.api_key {
let local_var_key = local_var_apikey.key.clone();
let local_var_value = match local_var_apikey.prefix {
Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key),
None => local_var_key,
};
local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value);
};
local_var_req_builder = local_var_req_builder.json(&body);
let local_var_req = local_var_req_builder.build()?;
let local_var_resp = local_var_client.execute(local_var_req).await?;
let local_var_status = local_var_resp.status();
let local_var_content = local_var_resp.text().await?;
if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
serde_json::from_str(&local_var_content).map_err(Error::from)
} else {
let local_var_entity: Option<UpdateTestPauseStatusError> = serde_json::from_str(&local_var_content).ok();
let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
Err(Error::ResponseError(local_var_error))
}
}
|
fn main(){
enum Temp{
hot,
normal,
cold,
}
fn calc_temp(t: Temp) -> i32{
match t {
Temp::hot => 39,
Temp::normal => 36,
_ => 34,
}
}
let temp = Temp::cold;
println!("{}", calc_temp(temp));
} |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT license.
*/
use std::env;
use diskann::{
common::{ANNError, ANNResult},
index::ann_disk_index::create_disk_index,
model::{
default_param_vals::ALPHA,
vertex::{DIM_104, DIM_128, DIM_256},
DiskIndexBuildParameters, IndexConfiguration, IndexWriteParametersBuilder,
},
storage::DiskIndexStorage,
utils::round_up,
utils::{load_metadata_from_file, Timer},
};
use vector::{FullPrecisionDistance, Half, Metric};
/// The main function to build a disk index
#[allow(clippy::too_many_arguments)]
fn build_disk_index<T>(
metric: Metric,
data_path: &str,
r: u32,
l: u32,
index_path_prefix: &str,
num_threads: u32,
search_ram_limit_gb: f64,
index_build_ram_limit_gb: f64,
num_pq_chunks: usize,
use_opq: bool,
) -> ANNResult<()>
where
T: Default + Copy + Sync + Send + Into<f32>,
[T; DIM_104]: FullPrecisionDistance<T, DIM_104>,
[T; DIM_128]: FullPrecisionDistance<T, DIM_128>,
[T; DIM_256]: FullPrecisionDistance<T, DIM_256>,
{
let disk_index_build_parameters =
DiskIndexBuildParameters::new(search_ram_limit_gb, index_build_ram_limit_gb)?;
let index_write_parameters = IndexWriteParametersBuilder::new(l, r)
.with_saturate_graph(true)
.with_num_threads(num_threads)
.build();
let (data_num, data_dim) = load_metadata_from_file(data_path)?;
let config = IndexConfiguration::new(
metric,
data_dim,
round_up(data_dim as u64, 8_u64) as usize,
data_num,
num_pq_chunks > 0,
num_pq_chunks,
use_opq,
0,
1f32,
index_write_parameters,
);
let storage = DiskIndexStorage::new(data_path.to_string(), index_path_prefix.to_string())?;
let mut index = create_disk_index::<T>(Some(disk_index_build_parameters), config, storage)?;
let timer = Timer::new();
index.build("")?;
let diff = timer.elapsed();
println!("Indexing time: {}", diff.as_secs_f64());
Ok(())
}
fn main() -> ANNResult<()> {
let mut data_type = String::new();
let mut dist_fn = String::new();
let mut data_path = String::new();
let mut index_path_prefix = String::new();
let mut num_threads = 0u32;
let mut r = 64u32;
let mut l = 100u32;
let mut search_ram_limit_gb = 0f64;
let mut index_build_ram_limit_gb = 0f64;
let mut build_pq_bytes = 0u32;
let mut use_opq = false;
let args: Vec<String> = env::args().collect();
let mut iter = args.iter().skip(1).peekable();
while let Some(arg) = iter.next() {
match arg.as_str() {
"--help" | "-h" => {
print_help();
return Ok(());
}
"--data_type" => {
data_type = iter
.next()
.ok_or_else(|| {
ANNError::log_index_config_error(
"data_type".to_string(),
"Missing data type".to_string(),
)
})?
.to_owned();
}
"--dist_fn" => {
dist_fn = iter
.next()
.ok_or_else(|| {
ANNError::log_index_config_error(
"dist_fn".to_string(),
"Missing distance function".to_string(),
)
})?
.to_owned();
}
"--data_path" => {
data_path = iter
.next()
.ok_or_else(|| {
ANNError::log_index_config_error(
"data_path".to_string(),
"Missing data path".to_string(),
)
})?
.to_owned();
}
"--index_path_prefix" => {
index_path_prefix = iter
.next()
.ok_or_else(|| {
ANNError::log_index_config_error(
"index_path_prefix".to_string(),
"Missing index path prefix".to_string(),
)
})?
.to_owned();
}
"--max_degree" | "-R" => {
r = iter
.next()
.ok_or_else(|| {
ANNError::log_index_config_error(
"max_degree".to_string(),
"Missing max degree".to_string(),
)
})?
.parse()
.map_err(|err| {
ANNError::log_index_config_error(
"max_degree".to_string(),
format!("ParseIntError: {}", err),
)
})?;
}
"--Lbuild" | "-L" => {
l = iter
.next()
.ok_or_else(|| {
ANNError::log_index_config_error(
"Lbuild".to_string(),
"Missing build complexity".to_string(),
)
})?
.parse()
.map_err(|err| {
ANNError::log_index_config_error(
"Lbuild".to_string(),
format!("ParseIntError: {}", err),
)
})?;
}
"--num_threads" | "-T" => {
num_threads = iter
.next()
.ok_or_else(|| {
ANNError::log_index_config_error(
"num_threads".to_string(),
"Missing number of threads".to_string(),
)
})?
.parse()
.map_err(|err| {
ANNError::log_index_config_error(
"num_threads".to_string(),
format!("ParseIntError: {}", err),
)
})?;
}
"--build_PQ_bytes" => {
build_pq_bytes = iter
.next()
.ok_or_else(|| {
ANNError::log_index_config_error(
"build_PQ_bytes".to_string(),
"Missing PQ bytes".to_string(),
)
})?
.parse()
.map_err(|err| {
ANNError::log_index_config_error(
"build_PQ_bytes".to_string(),
format!("ParseIntError: {}", err),
)
})?;
}
"--use_opq" => {
use_opq = iter
.next()
.ok_or_else(|| {
ANNError::log_index_config_error(
"use_opq".to_string(),
"Missing use_opq flag".to_string(),
)
})?
.parse()
.map_err(|err| {
ANNError::log_index_config_error(
"use_opq".to_string(),
format!("ParseBoolError: {}", err),
)
})?;
}
"--search_DRAM_budget" | "-B" => {
search_ram_limit_gb = iter
.next()
.ok_or_else(|| {
ANNError::log_index_config_error(
"search_DRAM_budget".to_string(),
"Missing search_DRAM_budget flag".to_string(),
)
})?
.parse()
.map_err(|err| {
ANNError::log_index_config_error(
"search_DRAM_budget".to_string(),
format!("ParseBoolError: {}", err),
)
})?;
}
"--build_DRAM_budget" | "-M" => {
index_build_ram_limit_gb = iter
.next()
.ok_or_else(|| {
ANNError::log_index_config_error(
"build_DRAM_budget".to_string(),
"Missing build_DRAM_budget flag".to_string(),
)
})?
.parse()
.map_err(|err| {
ANNError::log_index_config_error(
"build_DRAM_budget".to_string(),
format!("ParseBoolError: {}", err),
)
})?;
}
_ => {
return Err(ANNError::log_index_config_error(
String::from(""),
format!("Unknown argument: {}", arg),
));
}
}
}
if data_type.is_empty()
|| dist_fn.is_empty()
|| data_path.is_empty()
|| index_path_prefix.is_empty()
{
return Err(ANNError::log_index_config_error(
String::from(""),
"Missing required arguments".to_string(),
));
}
let metric = dist_fn
.parse::<Metric>()
.map_err(|err| ANNError::log_index_config_error("dist_fn".to_string(), err.to_string()))?;
println!(
"Starting index build with R: {} Lbuild: {} alpha: {} #threads: {} search_DRAM_budget: {} build_DRAM_budget: {}",
r, l, ALPHA, num_threads, search_ram_limit_gb, index_build_ram_limit_gb
);
let err = match data_type.as_str() {
"int8" => build_disk_index::<i8>(
metric,
&data_path,
r,
l,
&index_path_prefix,
num_threads,
search_ram_limit_gb,
index_build_ram_limit_gb,
build_pq_bytes as usize,
use_opq,
),
"uint8" => build_disk_index::<u8>(
metric,
&data_path,
r,
l,
&index_path_prefix,
num_threads,
search_ram_limit_gb,
index_build_ram_limit_gb,
build_pq_bytes as usize,
use_opq,
),
"float" => build_disk_index::<f32>(
metric,
&data_path,
r,
l,
&index_path_prefix,
num_threads,
search_ram_limit_gb,
index_build_ram_limit_gb,
build_pq_bytes as usize,
use_opq,
),
"f16" => build_disk_index::<Half>(
metric,
&data_path,
r,
l,
&index_path_prefix,
num_threads,
search_ram_limit_gb,
index_build_ram_limit_gb,
build_pq_bytes as usize,
use_opq,
),
_ => {
println!("Unsupported type. Use one of int8, uint8, float or f16.");
return Err(ANNError::log_index_config_error(
"data_type".to_string(),
"Invalid data type".to_string(),
));
}
};
match err {
Ok(_) => {
println!("Index build completed successfully");
Ok(())
}
Err(err) => {
eprintln!("Error: {:?}", err);
Err(err)
}
}
}
fn print_help() {
println!("Arguments");
println!("--help, -h Print information on arguments");
println!("--data_type data type <int8/uint8/float> (required)");
println!("--dist_fn distance function <l2/cosine> (required)");
println!("--data_path Input data file in bin format (required)");
println!("--index_path_prefix Path prefix for saving index file components (required)");
println!("--max_degree, -R Maximum graph degree (default: 64)");
println!("--Lbuild, -L Build complexity, higher value results in better graphs (default: 100)");
println!("--search_DRAM_budget Bound on the memory footprint of the index at search time in GB. Once built, the index will use up only the specified RAM limit, the rest will reside on disk");
println!("--build_DRAM_budget Limit on the memory allowed for building the index in GB");
println!("--num_threads, -T Number of threads used for building index (defaults to num of CPU logic cores)");
println!("--build_PQ_bytes Number of PQ bytes to build the index; 0 for full precision build (default: 0)");
println!("--use_opq Set true for OPQ compression while using PQ distance comparisons for building the index, and false for PQ compression (default: false)");
}
|
use std::{borrow::Cow, collections::HashMap};
use serde::Serialize;
use crate::{context::Context, shared_strings::SharedStringIndex};
#[derive(Default, Serialize)]
pub(crate) struct Cells {
pub(crate) next_col_index: ColIndex,
pub(crate) cells: HashMap<ColIndex, Cell>,
}
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Serialize)]
pub struct ColIndex(pub usize);
#[derive(Serialize)]
pub struct Cell {
pub(crate) col_index: ColIndex,
pub(crate) cell_type: CellType,
}
#[derive(Serialize)]
#[serde(tag = "t", content = "c")]
pub(crate) enum CellType {
String(SharedStringIndex),
Number(Number),
}
#[derive(Serialize)]
#[serde(untagged)]
pub enum Number {
I8(i8),
U8(u8),
I16(i16),
U16(u16),
I32(i32),
U32(u32),
I64(i64),
U64(u64),
Isize(isize),
Usize(usize),
I128(i128),
U128(u128),
F32(f32),
F64(f64),
}
impl Cells {
pub(crate) fn add_str_cell(
&mut self,
context: &mut Context,
cell_value: Cow<'static, str>,
) -> &mut Cell {
self.set_str_cell(context, self.next_col_index, cell_value)
}
pub(crate) fn set_str_cell(
&mut self,
context: &mut Context,
col_index: ColIndex,
cell_value: Cow<'static, str>,
) -> &mut Cell {
let shared_string_index = context.add_shared_string(cell_value);
self.set_cell(
context,
Cell {
col_index,
cell_type: CellType::String(shared_string_index),
},
)
}
pub(crate) fn add_num_cell(&mut self, context: &mut Context, cell_value: Number) -> &mut Cell {
self.set_num_cell(context, self.next_col_index, cell_value)
}
pub(crate) fn set_num_cell(
&mut self,
context: &mut Context,
col_index: ColIndex,
cell_value: Number,
) -> &mut Cell {
self.set_cell(
context,
Cell {
col_index,
cell_type: CellType::Number(cell_value),
},
)
}
pub(crate) fn set_cell(&mut self, context: &mut Context, cell: Cell) -> &mut Cell {
let col_index = cell.col_index;
if col_index.0 >= self.next_col_index.0 {
self.next_col_index = ColIndex(col_index.0 + 1);
}
context.add_col_index(col_index);
self.cells.insert(col_index, cell);
self.cells.get_mut(&col_index).unwrap()
}
}
|
use crate::{
app::{
settings::Settings,
sound::{SoundDevice, ZXSample, CHANNEL_COUNT, DEFAULT_LATENCY, DEFAULT_SAMPLE_RATE},
},
backends::SDL_CONTEXT,
};
use sdl2::audio::{AudioCallback, AudioDevice, AudioSpecDesired};
use std::sync::mpsc;
/// Struct which used in SDL audio callback
struct SdlCallback {
samples: mpsc::Receiver<ZXSample>,
}
impl AudioCallback for SdlCallback {
type Channel = f32;
/// main callback function
fn callback(&mut self, out: &mut [f32]) {
for chunk in out.chunks_mut(CHANNEL_COUNT) {
// recieve samples from channel
if let Ok(sample) = self.samples.try_recv() {
chunk[0] = sample.left;
chunk[1] = sample.right;
} else {
chunk[0] = 0f32;
chunk[1] = 0f32;
}
}
}
}
/// Represents SDL audio backend
pub struct SoundSdl {
sender: mpsc::Sender<ZXSample>,
sample_rate: usize,
_device: AudioDevice<SdlCallback>, // Should be alive until Drop invocation
}
impl SoundSdl {
/// constructs sound backend from settings
pub fn new(settings: &Settings) -> anyhow::Result<SoundSdl> {
let mut audio_subsystem = None;
SDL_CONTEXT.with(|sdl| {
audio_subsystem = sdl.borrow_mut().audio().ok();
});
let audio = audio_subsystem
.ok_or_else(|| anyhow::anyhow!("Failed to initialize SDL audio backend"))?;
// Basically, SDL shits its pants if desired sound sample rate is not specified
let sample_rate = settings.sound_sample_rate.unwrap_or(DEFAULT_SAMPLE_RATE);
// SDL sets awfully big latency by default
let latency = settings.sound_latency.unwrap_or(DEFAULT_LATENCY);
let desired_spec = AudioSpecDesired {
freq: Some(sample_rate as i32),
channels: Some(CHANNEL_COUNT as u8),
samples: Some(latency as u16),
};
let (tx, rx) = mpsc::channel();
let device_handle = audio
.open_playback(None, &desired_spec, |_| SdlCallback { samples: rx })
.map_err(|e| anyhow::anyhow!("Failed to start SDL sound stream: {}", e))?;
device_handle.resume();
Ok(SoundSdl {
sender: tx,
sample_rate,
_device: device_handle,
})
}
}
impl SoundDevice for SoundSdl {
fn send_sample(&mut self, sample: ZXSample) {
self.sender.send(sample).unwrap();
}
fn sample_rate(&self) -> usize {
self.sample_rate
}
}
|
// Copyright © 2017, ACM@UIUC
//
// This file is part of the Groot Project.
//
// The Groot Project is open source software, released under the
// University of Illinois/NCSA Open Source License. You should have
// received a copy of this license in a file with the distribution.
extern crate hyper;
use hyper::*;
use std::io::Read;
struct Heart {
String Applications;
}
impl Heartbeat {
pub fn Beat() {
let client = Client::new();
let res = client.post("http://localhost:3000/set").body(r#"{ "msg": "Just trust the Rust" }"#).send().unwrap();
assert_eq!(res.status, hyper::Ok);
let mut res = client.get("http://localhost:3000/").send().unwrap();
assert_eq!(res.status, hyper::Ok);
let mut s = String::new();
res.read_to_string(&mut s).unwrap();
println!("{}", s);
}
pub fn new(String: Apps) -> self {
Heart {Applications: Apps}
}
}
|
use std::fs::{File, OpenOptions};
use std::io::prelude::*;
use std::path::PathBuf;
use toml;
use gpg::{GPG};
use std::os::unix::fs::OpenOptionsExt;
use PROTECTED_MODE;
use std::error::Error;
use secstr::SecStr;
#[derive(Serialize, Deserialize, Debug)]
pub struct EncryptedPassword {
username: Option<String>, // Username associated with the password.
email: Option<String>, // Email address assciated with the password.
comment: Option<String>, // Any comments the user may wish to include.
cipher_text: String, // The encrypted password itself.
}
/// An encrypted password and its meta-data.
impl EncryptedPassword {
pub fn new(username: Option<String>,
email: Option<String>,
comment: Option<String>,
cipher_text: String) -> Self {
Self { username, email, comment, cipher_text }
}
/// Write a password to disk. If `new` is `true` then the on-disk file must not already exist.
pub fn to_disk(&self, path: PathBuf, new: bool) -> Result<(), Box<Error>> {
let tml = toml::to_vec(self)?;
let mut opts = OpenOptions::new();
opts.write(true)
.mode(PROTECTED_MODE)
.truncate(true);
if new {
opts.create_new(true);
}
let mut pw_file = opts.open(path)?;
Ok(pw_file.write_all(&tml)?)
}
pub fn username<'a>(&'a self) -> Option<&'a str> {
self.username.as_ref().map(|s| s.as_str())
}
pub fn email(&self) -> Option<&str> {
self.email.as_ref().map(|s| s.as_str())
}
pub fn comment(&self) -> Option<&str> {
self.comment.as_ref().map(|s| s.as_str())
}
/// Reads a password in from the given filesystem path.
pub fn from_file(path: PathBuf) -> Result<Self, Box<Error>> {
let mut fh = File::open(path)?;
let mut pw_s: String = String::new();
fh.read_to_string(&mut pw_s)?;
Ok(toml::from_str(&pw_s)?)
}
/// Consumes and decrypts the password returning a `ClearPassword`.
pub fn decrypt(self, gpg: &mut GPG) -> Result<ClearPassword, Box<Error>> {
let clear_text = gpg.decrypt_string(&self.cipher_text)?;
Ok(ClearPassword {
username: self.username,
email: self.email,
comment: self.comment,
clear_text: clear_text,
})
}
/// Edits a password file.
/// If the password cipher text is to be updated, a new `Self` instance is returned, otherwise
/// the existing one is mutated and returned.
pub fn edit(mut self, edit: PasswordEdit, gpg: &mut GPG, encrypt_to: &Vec<String>)
-> Result<Self, Box<Error>> {
if let Some(username) = edit.username {
if username == "" {
self.username = None;
} else {
self.username = Some(username);
}
}
if let Some(email) = edit.email {
if email == "" {
self.email = None;
} else {
self.email = Some(email);
}
}
if let Some(comment) = edit.comment {
if comment == "" {
self.comment = None;
} else {
self.comment = Some(comment);
}
}
if let Some(clear_text) = edit.clear_text {
// Rather then decrypting the old value mutating it, we make a new instance altogether.
let cpw = ClearPassword::new(self.username, self.email, self.comment, clear_text);
Ok(cpw.encrypt(gpg, encrypt_to)?)
} else {
Ok(self)
}
}
}
/// A clear text password and its meta-data.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ClearPassword {
username: Option<String>, // Username associated with the password.
email: Option<String>, // Email address associated with the password.
comment: Option<String>, // Any comments the user may wish to include.
clear_text: SecStr, // The password text in the clear.
}
/// An unencrypted password and its meta-data.
impl ClearPassword {
pub fn new(username: Option<String>,
email: Option<String>,
comment: Option<String>,
clear_text: SecStr) -> Self {
Self { username, email, comment, clear_text }
}
pub fn clear_text(&self) -> &SecStr {
&self.clear_text
}
/// Consumes and encrypts the password returning an `EncryptedPassword`.
pub fn encrypt(self, gpg: &mut GPG, encrypt_to: &Vec<String>)
-> Result<EncryptedPassword, Box<Error>> {
let cipher_text = gpg.encrypt_string(&self.clear_text, encrypt_to)?;
Ok(EncryptedPassword::new(self.username,
self.email,
self.comment,
cipher_text))
}
pub fn username<'a>(&'a self) -> Option<&'a str> {
self.username.as_ref().map(|s| s.as_str())
}
pub fn email(&self) -> Option<&str> {
self.email.as_ref().map(|s| s.as_str())
}
pub fn comment(&self) -> Option<&str> {
self.comment.as_ref().map(|s| s.as_str())
}
}
/// A password edit description. Here a `None` means "no change".
/// The fields have the same meaning as `ClearPassword`. Unlike `ClearPassword`, all fields are
/// optional, since the user may choose to not change anything.
#[derive(Debug)]
pub struct PasswordEdit {
username: Option<String>,
email: Option<String>,
comment: Option<String>,
clear_text: Option<SecStr>,
}
impl PasswordEdit {
pub fn new(username: Option<String>,
email: Option<String>,
comment: Option<String>,
clear_text: Option<SecStr>) -> Self {
Self {
username: username.map(|a| a.into()),
email: email.map(|a| a.into()),
comment: comment.map(|a| a.into()),
clear_text: clear_text.map(|a| a.into()),
}
}
}
|
#![feature(marker_trait_attr, termination_trait_lib)]
#[macro_use]
extern crate log;
mod ingame;
pub mod state_machine;
pub use rsc2_pb::protocol;
use std::io;
use rsc2_pb::codec::Codec;
use tokio::net::TcpStream;
use tokio_util::codec::Framed;
pub type Connection = Framed<TcpStream, Codec>;
pub async fn connect(addr: impl std::net::ToSocketAddrs) -> io::Result<Connection> {
use tokio_util::codec::FramedParts;
use websocket_lite::ClientBuilder;
let addr = format!(
"ws://{}/sc2api",
addr.to_socket_addrs()
.ok()
.as_mut()
.and_then(Iterator::next)
.unwrap()
);
let client = ClientBuilder::new(&addr).map(ClientBuilder::async_connect_insecure);
match client {
Ok(client) => match client.await {
Ok(framed) => {
let FramedParts { io, codec, .. } = framed.into_parts();
Ok(Framed::from_parts(FramedParts::new::<
rsc2_pb::protocol::Request,
>(io, Codec::from(codec))))
}
Err(e) => Err(io::Error::new(io::ErrorKind::ConnectionRefused, e)),
},
Err(_) => Err(io::Error::new(
io::ErrorKind::InvalidInput,
"invalid address",
)),
}
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::ffi::CStr;
/// Path to the sabre executable. Needed for intercepting syscalls after execve.
static mut SABRE_PATH: *const libc::c_char = core::ptr::null();
/// Path to this plugin. Needed for intercepting syscalls after execve.
static mut PLUGIN_PATH: *const libc::c_char = core::ptr::null();
/// Path to the client binary.
static mut CLIENT_PATH: *const libc::c_char = core::ptr::null();
/// Sets the global path to the sabre binary.
#[doc(hidden)]
#[inline]
pub(super) unsafe fn set_sabre_path(path: *const libc::c_char) {
SABRE_PATH = path;
}
/// Sets the global path to the plugin (aka tool).
#[doc(hidden)]
#[inline]
pub(super) unsafe fn set_plugin_path(path: *const libc::c_char) {
PLUGIN_PATH = path;
}
/// Sets the global path to the client binary.
#[doc(hidden)]
#[inline]
pub(super) unsafe fn set_client_path(path: *const libc::c_char) {
CLIENT_PATH = path;
}
/// Returns the path to the sabre binary.
pub fn sabre_path() -> &'static CStr {
unsafe { CStr::from_ptr(SABRE_PATH) }
}
/// Returns the path to the plugin.
pub fn plugin_path() -> &'static CStr {
unsafe { CStr::from_ptr(PLUGIN_PATH) }
}
/// Returns the path to the client binary.
pub fn client_path() -> &'static CStr {
unsafe { CStr::from_ptr(CLIENT_PATH) }
}
|
#[doc = "Register `GICD_ICACTIVER1` reader"]
pub type R = crate::R<GICD_ICACTIVER1_SPEC>;
#[doc = "Register `GICD_ICACTIVER1` writer"]
pub type W = crate::W<GICD_ICACTIVER1_SPEC>;
#[doc = "Field `ICACTIVER1` reader - ICACTIVER1"]
pub type ICACTIVER1_R = crate::FieldReader<u32>;
#[doc = "Field `ICACTIVER1` writer - ICACTIVER1"]
pub type ICACTIVER1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 32, O, u32>;
impl R {
#[doc = "Bits 0:31 - ICACTIVER1"]
#[inline(always)]
pub fn icactiver1(&self) -> ICACTIVER1_R {
ICACTIVER1_R::new(self.bits)
}
}
impl W {
#[doc = "Bits 0:31 - ICACTIVER1"]
#[inline(always)]
#[must_use]
pub fn icactiver1(&mut self) -> ICACTIVER1_W<GICD_ICACTIVER1_SPEC, 0> {
ICACTIVER1_W::new(self)
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
}
#[doc = "For interrupts ID\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gicd_icactiver1::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`gicd_icactiver1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."]
pub struct GICD_ICACTIVER1_SPEC;
impl crate::RegisterSpec for GICD_ICACTIVER1_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [`gicd_icactiver1::R`](R) reader structure"]
impl crate::Readable for GICD_ICACTIVER1_SPEC {}
#[doc = "`write(|w| ..)` method takes [`gicd_icactiver1::W`](W) writer structure"]
impl crate::Writable for GICD_ICACTIVER1_SPEC {
const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0;
}
#[doc = "`reset()` method sets GICD_ICACTIVER1 to value 0"]
impl crate::Resettable for GICD_ICACTIVER1_SPEC {
const RESET_VALUE: Self::Ux = 0;
}
|
use crate::data::{Entry, Item, Status};
use crate::handler::Only;
use crate::path::try_strip_prefix;
use crate::{files, path_str};
use anyhow::Result;
use glob::Pattern as GlobPattern;
use std::path::{Path, PathBuf};
#[cfg(test)]
mod tests;
pub struct Indexer {
// The path to the users home directory.
home: PathBuf,
home_str: String,
// The path to the repository to sync files to.
repo: PathBuf,
repo_str: String,
ignore_patterns: Vec<GlobPattern>,
only: Option<Only>,
}
impl Indexer {
pub fn new(home: PathBuf, repo: PathBuf, only: Option<Only>) -> Self {
let home_str = path_str!(home);
let repo_str = path_str!(repo);
Self {
home,
home_str,
repo,
repo_str,
// TODO: read these from files
// - .gitignore
// - .ignore
ignore_patterns: vec![
GlobPattern::new("*/.git/*").unwrap(),
GlobPattern::new("*/node_modules/*").unwrap(),
GlobPattern::new("*/target/*").unwrap(),
GlobPattern::new("*.o").unwrap(),
GlobPattern::new("*.backup").unwrap(),
// Python
GlobPattern::new("/*__pycache__/*").unwrap(),
GlobPattern::new("*/.venv/*").unwrap(),
],
only,
}
}
pub fn index(&self, items: &[Item]) -> Result<Vec<(String, Vec<Entry>)>> {
let mut entries: Vec<(String, Vec<Entry>)> = Vec::new();
for item in items {
let t = self.process_item(item)?;
// TODO: refactor
let mut filtered = Vec::new();
if let Some(only) = &self.only {
for entry in t {
if let Entry::Ok { relpath, .. } = &entry {
for pattern in &only.patterns {
if pattern.matches(relpath) {
filtered.push(entry);
break;
}
}
}
}
} else {
filtered = t;
}
entries.push((item.name.clone(), filtered));
}
entries.sort_by(|(a, _), (b, _)| a.partial_cmp(b).unwrap());
Ok(entries)
}
fn process_item(&self, item: &Item) -> Result<Vec<Entry>> {
log::debug!("Processing item: {:?}", item);
let ps = match item.ignore_patterns()? {
None => vec![],
Some(ps) => ps,
};
let mut entries = Vec::new();
for path in &item.files {
let filepath = path_str!(path);
let home_path = self.home.join(&filepath);
let repo_path = self.repo.join(&filepath);
if is_glob(&filepath) {
let es = self.process_glob(&filepath, &ps)?;
entries.extend(es);
continue;
}
if !(home_path.exists() || repo_path.exists()) {
let entry =
Entry::new_err("does not exists in either home or repository".to_string());
return Ok(vec![entry]);
}
if home_path.is_dir() || repo_path.is_dir() {
let fixed = match filepath.strip_suffix('/') {
Some(s) => format!("{}/*", s),
None => format!("{}/*", filepath),
};
let entry = Entry::new_err(format!(
"use glob pattern (fix: change {} to {})",
filepath, fixed,
));
return Ok(vec![entry]);
}
if let Some(entry) = self.make_entry(&filepath, home_path, repo_path)? {
entries.push(entry);
}
}
Ok(entries)
}
fn process_glob(
&self,
globpattern: &str,
ignore_patterns: &[GlobPattern],
) -> Result<Vec<Entry>> {
let mut entries = Vec::new();
let home_glob_path = self.home.join(globpattern);
let repo_glob_path = self.repo.join(globpattern);
let home_str = path_str!(home_glob_path);
let repo_str = path_str!(repo_glob_path);
let home_glob = glob::glob(&home_str);
let repo_glob = glob::glob(&repo_str);
if home_glob.is_err() || repo_glob.is_err() {
let entry = Entry::new_err(format!("invalid glob pattern: {}", globpattern));
return Ok(vec![entry]);
}
let mut home_files: Vec<String> = Vec::new();
for p in home_glob.unwrap().flatten() {
if p.is_file() {
let s = try_strip_prefix(&self.home_str, &path_str!(&p));
if should_ignore(&s, &self.ignore_patterns) {
continue;
}
if !ignore_patterns.is_empty() && should_ignore(&s, ignore_patterns) {
continue;
}
log::debug!("Adding home file: {s}");
home_files.push(s.to_string());
}
}
let mut repo_files: Vec<String> = Vec::new();
for p in repo_glob.unwrap().flatten() {
if p.is_file() {
let s = try_strip_prefix(&self.repo_str, &path_str!(&p));
if should_ignore(&s, &self.ignore_patterns) {
continue;
}
if !ignore_patterns.is_empty() && should_ignore(&s, ignore_patterns) {
continue;
}
log::debug!("Adding repo file: {s}");
repo_files.push(s.to_string());
}
}
let both: Vec<&String> = home_files
.iter()
.filter(|s| repo_files.contains(s))
.collect();
let home_only: Vec<&String> = home_files
.iter()
.filter(|s| !repo_files.contains(s))
.collect();
let repo_only: Vec<&String> = repo_files
.iter()
.filter(|s| !home_files.contains(s))
.collect();
let mut add_entry = |path: &str, status: Option<Status>| -> Result<()> {
let h = self.home.join(path);
let r = self.repo.join(path);
match status {
Some(status) => {
let entry = Entry::new(path, status, h, r)?;
entries.push(entry);
}
None => {
if let Some(entry) = self.make_entry(path, h, r)? {
entries.push(entry);
}
}
}
Ok(())
};
for s in both {
add_entry(s, None)?;
}
for s in home_only {
add_entry(s, Some(Status::MissingRepo))?;
}
for s in repo_only {
add_entry(s, Some(Status::MissingHome))?;
}
Ok(entries)
}
fn make_entry(
&self,
filepath: &str,
home_path: PathBuf,
repo_path: PathBuf,
) -> Result<Option<Entry>> {
if home_path.ends_with("backup") {
return Ok(None);
}
let status = get_status(&home_path, &repo_path)?;
let entry = Entry::new(filepath, status, home_path, repo_path)?;
Ok(Some(entry))
}
}
fn get_status(home_path: &Path, repo_path: &Path) -> Result<Status> {
let status = if !home_path.exists() {
Status::MissingHome
} else if !repo_path.exists() {
Status::MissingRepo
} else {
let s = files::read_string(home_path)?;
let hash_src = files::digest(s.as_bytes())?;
let s = files::read_string(repo_path)?;
let hash_dst = files::digest(s.as_bytes())?;
if hash_src.eq(&hash_dst) {
Status::Ok
} else {
Status::Diff
}
};
Ok(status)
}
fn should_ignore(path: &str, patterns: &[GlobPattern]) -> bool {
patterns.iter().any(|p| p.matches(path))
}
pub fn is_glob(s: &str) -> bool {
s.contains('*')
}
|
use crate::runtime_api::StateRootExtractor;
use sp_api::ProvideRuntimeApi;
use sp_blockchain::{Error, HeaderBackend};
use sp_domains::DomainsApi;
use sp_runtime::traits::{Block as BlockT, Header, NumberFor};
use std::sync::Arc;
/// Verifies if the xdm has the correct proof generated from known parent block.
/// This is used by the Domains to validate Extrinsics using their embeded consensus chain.
/// Returns either true if the XDM is valid else false.
/// Returns Error when required calls to fetch header info fails.
pub fn verify_xdm<CClient, CBlock, Block, SRE>(
consensus_client: &Arc<CClient>,
at: Block::Hash,
state_root_extractor: &SRE,
extrinsic: &Block::Extrinsic,
) -> Result<bool, Error>
where
CClient: HeaderBackend<CBlock> + ProvideRuntimeApi<CBlock> + 'static,
CClient::Api: DomainsApi<CBlock, NumberFor<Block>, Block::Hash>,
Block: BlockT,
CBlock: BlockT,
NumberFor<CBlock>: From<NumberFor<Block>>,
CBlock::Hash: From<Block::Hash>,
SRE: StateRootExtractor<Block>,
{
if let Ok(state_roots) = state_root_extractor.extract_state_roots(at, extrinsic) {
// verify consensus chain state root
if let Some(header) =
consensus_client.header(state_roots.consensus_chain_block_info.block_hash.into())?
{
if *header.state_root() != state_roots.consensus_chain_state_root.into() {
return Ok(false);
}
}
}
Ok(true)
}
|
use messagebus::{
derive::{Error as MbError, Message},
error, Bus, Handler, Message, Module,
};
use thiserror::Error;
#[derive(Debug, Error, MbError)]
enum Error {
#[error("Error({0})")]
Error(anyhow::Error),
}
impl<M: Message> From<error::Error<M>> for Error {
fn from(err: error::Error<M>) -> Self {
Self::Error(err.into())
}
}
#[derive(Debug, Clone, Message)]
struct MsgF32(pub f32);
#[derive(Debug, Clone, Message)]
struct MsgU32(pub u32);
#[derive(Debug, Clone, Message)]
struct MsgU16(pub u16);
struct TmpReceiver;
impl Handler<MsgF32> for TmpReceiver {
type Error = Error;
type Response = ();
fn handle(&self, msg: MsgF32, _bus: &Bus) -> Result<Self::Response, Self::Error> {
println!("---> f32 {:?}", msg);
std::thread::sleep(std::time::Duration::from_millis(100));
println!("done");
Ok(())
}
}
impl Handler<MsgU16> for TmpReceiver {
type Error = Error;
type Response = ();
fn handle(&self, msg: MsgU16, _bus: &Bus) -> Result<Self::Response, Self::Error> {
println!("---> u16 {:?}", msg);
Ok(())
}
}
impl Handler<MsgU32> for TmpReceiver {
type Error = Error;
type Response = ();
fn handle(&self, msg: MsgU32, _bus: &Bus) -> Result<Self::Response, Self::Error> {
println!("---> u32 {:?}", msg);
Ok(())
}
}
fn module() -> Module {
Module::new()
.register(TmpReceiver)
.subscribe_sync::<MsgF32>(8, Default::default())
.subscribe_sync::<MsgU16>(8, Default::default())
.subscribe_sync::<MsgU32>(8, Default::default())
.done()
}
#[tokio::test]
async fn test_sync() {
let (b, poller) = Bus::build().add_module(module()).build();
b.send(MsgF32(32f32)).await.unwrap();
b.send(MsgU16(11u16)).await.unwrap();
b.send(MsgU32(32u32)).await.unwrap();
b.flush_and_sync_all(false).await;
b.close().await;
poller.await;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.