text
stringlengths
8
4.13M
#![allow(dead_code)] #![allow(unused_variables)] fn ifstatement(){ let temp = 15; if temp > 30{ println!("hawt"); } else if temp < 10{ print!("coldlol"); } else { println!("ok"); } let day = if temp > 20{"sunny!"} else{"cloudy"}; //if statement can be expressed in the print macro as well println!("today is {}", day); } fn while_loop (){ let mut x = 1; while x < 1000{ x = x + 100; if x == 801 {continue; } println!("the value is {}", x) } let mut y = 1; loop { y = y + 100; println!("the valuea is {}", y); if y == 901 {break; } } } fn for_loop(){ for x in 1..11{ if x == 8 {break; } println!("x is equal to {}", x); } for (pos, y) in (30..41).enumerate(){ println!("{} : {}", pos, y); } } fn match_statement(){ let country_code = 58; // 1...999 let country = match country_code{ 44 => "UK", 46 => "Sweden", 372 => "Estonia", 1...999 => "Unknown", // .. vs ... - second includes last value in range _ => "invalid" }; println!("the country with code {} is {}", country_code, country); } pub fn main(){ //ifstatement(); //while_loop(); //for_loop(); //match_statement(); }
/// Constructs a new `Rc<T>` /// /// # Examples /// /// ``` /// use std::rc::Rc; /// /// let five = Rc::new(5); /// ``` /// /// ``` /// Simple `&str` patterns: /// /// ``` /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect(); /// assert_eq!(v, vec!["Mary", "had", "a", "little", "lamb"]); /// ``` /// /// More complex patterns with a lambda: /// /// ``` /// let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect(); /// assert_eq!(v, vec!["abc", "def", "ghi"]); /// ``` /// /// ```c /// printf("Hello world\n"); /// ``` /* use std::rc::Rc; pub fn new(value: T) ->Rc<T> { } */ /// The `Option` type. See [the module level documentation](../) for more. enum Option<T> { /// No value None, /// Some value `T` Some(T) } /* Following code could not be compiled because of the doc error /// The `Option1` type. See [the module level documentation](../) for more. enum Option1<T> { None, /// No value Some(T) /// Some value `T` } */ /// Panic with a given message unless an expression evaluates to true. /// /// # Example /// /// ``` /// # #[macro_use] extern crate foo; /// # fn main() { /// panic_unless!(1+1==2,"Math is broken."); /// # } /// ``` /// ```should_panic /// # #[macro_use] extern crate foo; /// # fn main() { /// panic_unless!(true==false, "I'm broken."); /// # } /// ``` #[macro_export] macro_rules! panic_unless { ($condition:exp, $($rest:expr),+) => ({if ! $condition { panic!($($rest),+);}}); }
use std::{ cmp::min, io, io::{BufReader, Read, Seek, SeekFrom}, }; pub struct ByteChunkIter<R> { pub start_byte_index: usize, end_byte_index_exclusive: usize, current_byte_index: usize, pub chunk_size: usize, buf: BufReader<R>, } impl<R: Seek> ByteChunkIter<R> { pub fn new( mut buf: BufReader<R>, start_byte_index: usize, end_byte_index_exclusive: usize, chunk_size: usize, ) -> ByteChunkIter<R> { let offset = buf.seek(SeekFrom::Start(start_byte_index as u64)).unwrap() as usize; assert_eq!(offset, start_byte_index); ByteChunkIter { start_byte_index, end_byte_index_exclusive, current_byte_index: start_byte_index, chunk_size, buf, } } } impl<R: Seek> Seek for ByteChunkIter<R> { fn seek(&mut self, seek_from: SeekFrom) -> io::Result<u64> { let offset_from_start = self.buf.seek(seek_from)?; self.current_byte_index = offset_from_start as usize; Ok(offset_from_start) } } impl<R: Read> Iterator for ByteChunkIter<R> { type Item = Vec<u8>; fn next(&mut self) -> Option<Self::Item> { if self.current_byte_index >= self.end_byte_index_exclusive { None } else { let len = min( self.end_byte_index_exclusive - self.current_byte_index, self.chunk_size, ); let mut bytes = vec![0u8; len]; self.buf.read_exact(bytes.as_mut_slice()).unwrap(); self.current_byte_index += len; Some(bytes) } } }
use crate::{grammar::Parser, SyntaxKind::*, T}; use super::ty_name; pub(crate) fn gen_arg_list(p: &mut Parser) { let m = p.start(); p.bump(T![<]); ty_name(p); while p.eat(T![,]) { ty_name(p); } p.expect(T![>]); m.complete(p, GENERIC_ARG_LIST); }
extern crate cargo_submodules_test; fn main() { println!("{:?}", cargo_submodules_test::foo()); }
use super::ByteRecord; use crate::{ array::{Primitive, PrimitiveArray}, datatypes::*, types::NativeType, }; pub trait PrimitiveParser<T: NativeType + lexical_core::FromLexical, E> { fn parse(&self, bytes: &[u8], _: &DataType, _: usize) -> Result<Option<T>, E> { // default behavior is infalible: `None` if unable to parse Ok(lexical_core::parse(bytes).ok()) } } /// creates a new [`PrimitiveArray`] from a slice of [`ByteRecord`]. pub fn new_primitive_array< T: NativeType + lexical_core::FromLexical, E, P: PrimitiveParser<T, E>, >( line_number: usize, rows: &[ByteRecord], col_idx: usize, data_type: &DataType, parser: &P, ) -> Result<PrimitiveArray<T>, E> { let iter = rows .iter() .enumerate() .map(|(row_index, row)| match row.get(col_idx) { Some(s) => { if s.is_empty() { return Ok(None); } parser.parse(s, &data_type, line_number + row_index) } None => Ok(None), }); Ok(Primitive::<T>::try_from_trusted_len_iter(iter)?.to(data_type.clone())) }
use proconio::input; fn main() { input! { n: usize, a: [u32; n], }; let ans = a.iter().sum::<u32>(); println!("{}", ans); }
// These are common OSM keys. Keys used in just one or two places don't really need to be defined // here. // These're normal OSM keys. pub const NAME: &str = "name"; pub const HIGHWAY: &str = "highway"; pub const MAXSPEED: &str = "maxspeed"; // The rest of these are all inserted by A/B Street to plumb data between different stages of map // construction. They could be plumbed another way, but this is the most convenient. // TODO Comparing to Some(&"true".to_string()) is annoying // Just a copy of OSM IDs, so that things displaying/searching tags will also pick these up. pub const OSM_WAY_ID: &str = "abst:osm_way_id"; pub const OSM_REL_ID: &str = "abst:osm_rel_id"; // OSM ways are split into multiple roads. The first and last road are marked, which is important // for interpreting turn restrictions. pub const ENDPT_FWD: &str = "abst:endpt_fwd"; pub const ENDPT_BACK: &str = "abst:endpt_back"; // Synthetic roads have (some of) these. pub const SYNTHETIC: &str = "abst:synthetic"; pub const SYNTHETIC_LANES: &str = "abst:synthetic_lanes"; pub const FWD_LABEL: &str = "abst:fwd_label"; pub const BACK_LABEL: &str = "abst:back_label"; // Synthetic buildings may have these. pub const LABEL: &str = "abst:label"; // Any roads might have these. pub const PARKING_LANE_FWD: &str = "abst:parking_lane_fwd"; pub const PARKING_LANE_BACK: &str = "abst:parking_lane_back";
//! Tests auto-converted from "sass-spec/spec/selector-functions/is_superselector" #[allow(unused)] use super::rsass; #[allow(unused)] use rsass::set_precision; /// From "sass-spec/spec/selector-functions/is_superselector/any_is_not_superselector_of_different_prefix" #[test] fn any_is_not_superselector_of_different_prefix() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: refute_superselector(\':-moz-any(.foo, .bar)\', \':-s-any(.foo, .bar)\');\n}" ) .unwrap(), "test {\n a: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/child_isnt_superselector_of_longer_child" #[test] fn child_isnt_superselector_of_longer_child() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: refute_superselector(\'.foo > .baz\', \'.foo > .bar > .baz\');\n b: refute_superselector(\'.foo > .baz\', \'.foo > .bar .baz\');\n}" ) .unwrap(), "test {\n a: true;\n b: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/complex_superselector" #[test] fn complex_superselector() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a : assert_strict_superselector(\'.bar\', \'.foo .bar\');\n b : assert_strict_superselector(\'.bar\', \'.foo > .bar\');\n c : assert_strict_superselector(\'.bar\', \'.foo + .bar\');\n d : assert_strict_superselector(\'.bar\', \'.foo ~ .bar\');\n}" ) .unwrap(), "test {\n a: true;\n b: true;\n c: true;\n d: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/compound_superselector" #[test] fn compound_superselector() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a : assert_strict_superselector(\'.foo\', \'.foo.bar\');\n b : assert_strict_superselector(\'.bar\', \'.foo.bar\');\n c : assert_strict_superselector(\'a\', \'a#b\');\n d : assert_strict_superselector(\'#b\', \'a#b\');\n}\n" ) .unwrap(), "test {\n a: true;\n b: true;\n c: true;\n d: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/current_is_superselector_with_identical_innards" #[test] fn current_is_superselector_with_identical_innards() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: is-superselector(\':current(.foo)\', \':current(.foo)\');\n}" ) .unwrap(), "test {\n a: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/current_is_superselector_with_subselector_innards" #[test] fn current_is_superselector_with_subselector_innards() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: not is-superselector(\':current(.foo)\', \':current(.foo.bar)\');\n b: not is-superselector(\':current(.foo.bar)\', \':current(.foo)\')\n}" ) .unwrap(), "test {\n a: true;\n b: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/descendant_is_superselector_of_child" #[test] fn descendant_is_superselector_of_child() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: assert_strict_superselector(\'.foo .bar\', \'.foo > .bar.baz\');\n b: assert_strict_superselector(\'.foo .bar\', \'.foo.baz > .bar\');\n c: assert_strict_superselector(\'.foo .baz\', \'.foo > .bar > .baz\');\n}" ) .unwrap(), "test {\n a: true;\n b: true;\n c: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/following_sibling_is_superselector_of_next_sibling" #[test] fn following_sibling_is_superselector_of_next_sibling() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: assert_strict_superselector(\'.foo ~ .bar\', \'.foo + .bar.baz\');\n b: assert_strict_superselector(\'.foo ~ .bar\', \'.foo.baz + .bar\');\n}" ) .unwrap(), "test {\n a: true;\n b: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/following_sibling_isnt_superselector_of_longer_following_sibling" #[test] fn following_sibling_isnt_superselector_of_longer_following_sibling() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: refute_superselector(\'.foo + .baz\', \'.foo + .bar + .baz\');\n b: refute_superselector(\'.foo + .baz\', \'.foo + .bar .baz\');\n}" ) .unwrap(), "test {\n a: true;\n b: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/has_is_superselector_of_subset_host" #[test] fn has_is_superselector_of_subset_host() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: assert_strict_superselector(\':has(.foo, .bar, .baz)\', \':has(.foo.bip, .baz.bang)\');\n}" ) .unwrap(), "test {\n a: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/host_context_is_superselector_of_subset_host" #[test] fn host_context_is_superselector_of_subset_host() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: assert_strict_superselector(\':host-context(.foo, .bar, .baz)\', \':host-context(.foo.bip, .baz.bang)\');\n}" ) .unwrap(), "test {\n a: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/host_is_superselector_of_subset_host" #[test] fn host_is_superselector_of_subset_host() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: assert_strict_superselector(\':host(.foo, .bar, .baz)\', \':host(.foo.bip, .baz.bang)\');\n}" ) .unwrap(), "test {\n a: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/leading_combinator" #[test] fn leading_combinator() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: refute_superselector(\'+ .foo\', \'.foo\');\n b: refute_superselector(\'+ .foo\', \'.bar + .foo\');\n}" ) .unwrap(), "test {\n a: true;\n b: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/matches_can_be_subselector" #[test] fn matches_can_be_subselector() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\n\n@function check_matches($a, $b) {\n $prefixes: matches -moz-any;\n $result: true;\n @each $name in $prefixes{\n @if (not assert_strict_superselector(\":#{$name}(#{$a})\", #{$b}) and $result == true) {\n $result: false;\n }\n }\n\n @return $result;\n}\n\ntest {\n a: check_matches(\'.foo\', \'.foo.bar\');\n b: check_matches(\'.foo, .bar\', \'.foo.bar.baz\');\n c: check_matches(\'.foo\', \'.foo.bar, .foo.baz\');\n}" ) .unwrap(), "test {\n a: true;\n b: true;\n c: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/matches_is_not_superselector_of_any" #[test] fn matches_is_not_superselector_of_any() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: refute_superselector(\':matches(.foo, .bar)\', \':-moz-any(.foo, .bar)\');\n b: refute_superselector(\':-moz-any(.foo, .bar)\', \':matches(.foo, .bar)\');\n}" ) .unwrap(), "test {\n a: true;\n b: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/matches_is_superselector_of_constituent_selectors" #[test] fn matches_is_superselector_of_constituent_selectors() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\n\n@function check_matches($a, $b) {\n $prefixes: matches -moz-any;\n $result: true;\n @each $name in $prefixes{\n @if (not assert_strict_superselector(\":#{$name}(#{$a})\", #{$b}) and $result == true) {\n $result: false;\n }\n }\n\n @return $result;\n}\n\ntest {\n a: check_matches(\'.foo, .bar\', \'.foo.baz\');\n b: check_matches(\'.foo, .bar\', \'.bar.baz\');\n c: check_matches(\".foo .bar, .baz\", \'.x .foo .bar\');\n}" ) .unwrap(), "test {\n a: true;\n b: true;\n c: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/matches_is_superselector_of_subset_matches" #[test] fn matches_is_superselector_of_subset_matches() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: assert_strict_superselector(\':matches(.foo, .bar, .baz)\', \'#x:matches(.foo.bip, .baz.bang)\');\n b: assert_strict_superselector(\':-moz-any(.foo, .bar, .baz)\', \'#x:-moz-any(.foo.bip, .baz.bang)\');\n}" ) .unwrap(), "test {\n a: true;\n b: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/matching_combinator" #[test] fn matching_combinator() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: assert_strict_superselector(\'.foo + .bar\', \'.foo + .bar.baz\');\n b: assert_strict_superselector(\'.foo + .bar\', \'.foo.baz + .bar\');\n c: assert_strict_superselector(\'.foo > .bar\', \'.foo > .bar.baz\');\n d: assert_strict_superselector(\'.foo > .bar\', \'.foo.baz > .bar\');\n e: assert_strict_superselector(\'.foo ~ .bar\', \'.foo ~ .bar.baz\');\n f: assert_strict_superselector(\'.foo ~ .bar\', \'.foo.baz ~ .bar\');\n}\n" ) .unwrap(), "test {\n a: true;\n b: true;\n c: true;\n d: true;\n e: true;\n f: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/not_is_not_superselector_of_non_unique_selectors" #[test] fn not_is_not_superselector_of_non_unique_selectors() { assert_eq!( rsass( "test {\n a: not is-superselector(\':not(.foo)\', \'.bar\');\n b: not is-superselector(\':not(:hover)\', \':visited\');\n}" ) .unwrap(), "test {\n a: true;\n b: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/nth_match_is_not_superselector_of_nth_last_match" #[test] fn nth_match_is_not_superselector_of_nth_last_match() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: refute_superselector(\':nth-child(2n of .foo, .bar)\', \':nth-last-child(2n of .foo, .bar)\');\n b: refute_superselector(\':nth-last-child(2n of .foo, .bar)\', \':nth-child(2n of .foo, .bar)\');\n}" ) .unwrap(), "test {\n a: true;\n b: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/nth_match_is_not_superselector_of_nth_match_with_different_arg" #[test] fn nth_match_is_not_superselector_of_nth_match_with_different_arg() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: refute_superselector(\':nth-child(2n of .foo, .bar, .baz)\', \'#x:nth-child(2n + 1 of .foo.bip, .baz.bang)\');\n b: refute_superselector(\':nth-last-child(2n of .foo, .bar, .baz)\', \'#x:nth-last-child(2n + 1 of .foo.bip, .baz.bang)\');\n}" ) .unwrap(), "test {\n a: true;\n b: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/reflexivity" #[test] fn reflexivity() { assert_eq!( rsass( "test {\n tag: is_superselector(\'h1\', \'h1\');\n class: is_superselector(\'.foo\', \'.foo\');\n descendant: is_superselector(\'#foo > .bar, baz\', \'#foo > .bar, baz\');\n }" ) .unwrap(), "test {\n tag: true;\n class: true;\n descendant: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/selector_list_subset" #[test] fn selector_list_subset() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: assert_strict_superselector(\'.foo, .bar\', \'.foo\');\n b: assert_strict_superselector(\'.foo, .bar, .baz\', \'.foo, .baz\');\n c: assert_strict_superselector(\'.foo, .baz, .qux\', \'.foo.bar, .baz.bang\');\n}" ) .unwrap(), "test {\n a: true;\n b: true;\n c: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/sibling_isnt_superselector_of_longer_sibling" #[test] fn sibling_isnt_superselector_of_longer_sibling() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\n// This actually is a superselector, but it\'s a very narrow edge case and\n// detecting it is very difficult and may be exponential in the worst case.\ntest {\n a: refute_superselector(\'.foo ~ .baz\', \'.foo ~ .bar ~ .baz\');\n b: refute_superselector(\'.foo ~ .baz\', \'.foo ~ .bar .baz\');\n}" ) .unwrap(), "test {\n a: true;\n b: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/trailing_combinator" #[test] fn trailing_combinator() { assert_eq!( rsass( "@import \"../assert_helpers\";\n\ntest {\n a: refute_superselector(\'.foo +\', \'.foo\');\n b: refute_superselector(\'.foo +\', \'.foo + .bar\');\n}" ) .unwrap(), "test {\n a: true;\n b: true;\n}\n" ); } /// From "sass-spec/spec/selector-functions/is_superselector/universal_superselector" #[test] fn universal_superselector() { assert_eq!( rsass( "universal-selector {\r\n test-01: is-superselector(\"*\", \"*\");\r\n test-02: is-superselector(\"|*\", \"*\");\r\n test-03: is-superselector(\"*|*\", \"*\");\r\n test-04: is-superselector(\"*\", \"|*\");\r\n test-05: is-superselector(\"|*\", \"|*\");\r\n test-06: is-superselector(\"*|*\", \"|*\");\r\n test-07: is-superselector(\"*\", \"*|*\");\r\n test-08: is-superselector(\"|*\", \"*|*\");\r\n test-09: is-superselector(\"*|*\", \"*|*\");\r\n}\r\n" ) .unwrap(), "universal-selector {\n test-01: true;\n test-02: false;\n test-03: false;\n test-04: false;\n test-05: true;\n test-06: false;\n test-07: false;\n test-08: false;\n test-09: true;\n}\n" ); }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "ApplicationModel_ExtendedExecution_Foreground")] pub mod Foreground; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct ExtendedExecutionReason(pub i32); impl ExtendedExecutionReason { pub const Unspecified: ExtendedExecutionReason = ExtendedExecutionReason(0i32); pub const LocationTracking: ExtendedExecutionReason = ExtendedExecutionReason(1i32); pub const SavingData: ExtendedExecutionReason = ExtendedExecutionReason(2i32); } impl ::core::convert::From<i32> for ExtendedExecutionReason { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ExtendedExecutionReason { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ExtendedExecutionReason { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.ExtendedExecution.ExtendedExecutionReason;i4)"); } impl ::windows::core::DefaultType for ExtendedExecutionReason { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct ExtendedExecutionResult(pub i32); impl ExtendedExecutionResult { pub const Allowed: ExtendedExecutionResult = ExtendedExecutionResult(0i32); pub const Denied: ExtendedExecutionResult = ExtendedExecutionResult(1i32); } impl ::core::convert::From<i32> for ExtendedExecutionResult { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ExtendedExecutionResult { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ExtendedExecutionResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.ExtendedExecution.ExtendedExecutionResult;i4)"); } impl ::windows::core::DefaultType for ExtendedExecutionResult { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ExtendedExecutionRevokedEventArgs(pub ::windows::core::IInspectable); impl ExtendedExecutionRevokedEventArgs { pub fn Reason(&self) -> ::windows::core::Result<ExtendedExecutionRevokedReason> { let this = self; unsafe { let mut result__: ExtendedExecutionRevokedReason = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ExtendedExecutionRevokedReason>(result__) } } } unsafe impl ::windows::core::RuntimeType for ExtendedExecutionRevokedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.ExtendedExecution.ExtendedExecutionRevokedEventArgs;{bfbc9f16-63b5-4c0b-aad6-828af5373ec3})"); } unsafe impl ::windows::core::Interface for ExtendedExecutionRevokedEventArgs { type Vtable = IExtendedExecutionRevokedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbfbc9f16_63b5_4c0b_aad6_828af5373ec3); } impl ::windows::core::RuntimeName for ExtendedExecutionRevokedEventArgs { const NAME: &'static str = "Windows.ApplicationModel.ExtendedExecution.ExtendedExecutionRevokedEventArgs"; } impl ::core::convert::From<ExtendedExecutionRevokedEventArgs> for ::windows::core::IUnknown { fn from(value: ExtendedExecutionRevokedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&ExtendedExecutionRevokedEventArgs> for ::windows::core::IUnknown { fn from(value: &ExtendedExecutionRevokedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ExtendedExecutionRevokedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ExtendedExecutionRevokedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ExtendedExecutionRevokedEventArgs> for ::windows::core::IInspectable { fn from(value: ExtendedExecutionRevokedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&ExtendedExecutionRevokedEventArgs> for ::windows::core::IInspectable { fn from(value: &ExtendedExecutionRevokedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ExtendedExecutionRevokedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ExtendedExecutionRevokedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for ExtendedExecutionRevokedEventArgs {} unsafe impl ::core::marker::Sync for ExtendedExecutionRevokedEventArgs {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct ExtendedExecutionRevokedReason(pub i32); impl ExtendedExecutionRevokedReason { pub const Resumed: ExtendedExecutionRevokedReason = ExtendedExecutionRevokedReason(0i32); pub const SystemPolicy: ExtendedExecutionRevokedReason = ExtendedExecutionRevokedReason(1i32); } impl ::core::convert::From<i32> for ExtendedExecutionRevokedReason { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for ExtendedExecutionRevokedReason { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for ExtendedExecutionRevokedReason { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.ApplicationModel.ExtendedExecution.ExtendedExecutionRevokedReason;i4)"); } impl ::windows::core::DefaultType for ExtendedExecutionRevokedReason { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ExtendedExecutionSession(pub ::windows::core::IInspectable); impl ExtendedExecutionSession { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<ExtendedExecutionSession, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn Reason(&self) -> ::windows::core::Result<ExtendedExecutionReason> { let this = self; unsafe { let mut result__: ExtendedExecutionReason = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ExtendedExecutionReason>(result__) } } pub fn SetReason(&self, value: ExtendedExecutionReason) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } pub fn Description(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetDescription<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn PercentProgress(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn SetPercentProgress(&self, value: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Foundation")] pub fn Revoked<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<::windows::core::IInspectable, ExtendedExecutionRevokedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveRevoked<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn RequestExtensionAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<ExtendedExecutionResult>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<ExtendedExecutionResult>>(result__) } } #[cfg(feature = "Foundation")] pub fn Close(&self) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<super::super::Foundation::IClosable>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } } unsafe impl ::windows::core::RuntimeType for ExtendedExecutionSession { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.ExtendedExecution.ExtendedExecutionSession;{af908a2d-118b-48f1-9308-0c4fc41e200f})"); } unsafe impl ::windows::core::Interface for ExtendedExecutionSession { type Vtable = IExtendedExecutionSession_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaf908a2d_118b_48f1_9308_0c4fc41e200f); } impl ::windows::core::RuntimeName for ExtendedExecutionSession { const NAME: &'static str = "Windows.ApplicationModel.ExtendedExecution.ExtendedExecutionSession"; } impl ::core::convert::From<ExtendedExecutionSession> for ::windows::core::IUnknown { fn from(value: ExtendedExecutionSession) -> Self { value.0 .0 } } impl ::core::convert::From<&ExtendedExecutionSession> for ::windows::core::IUnknown { fn from(value: &ExtendedExecutionSession) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ExtendedExecutionSession { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ExtendedExecutionSession { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ExtendedExecutionSession> for ::windows::core::IInspectable { fn from(value: ExtendedExecutionSession) -> Self { value.0 } } impl ::core::convert::From<&ExtendedExecutionSession> for ::windows::core::IInspectable { fn from(value: &ExtendedExecutionSession) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ExtendedExecutionSession { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a ExtendedExecutionSession { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<ExtendedExecutionSession> for super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: ExtendedExecutionSession) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } #[cfg(feature = "Foundation")] impl ::core::convert::TryFrom<&ExtendedExecutionSession> for super::super::Foundation::IClosable { type Error = ::windows::core::Error; fn try_from(value: &ExtendedExecutionSession) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for ExtendedExecutionSession { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> { ::windows::core::IntoParam::into_param(&self) } } #[cfg(feature = "Foundation")] impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::IClosable> for &ExtendedExecutionSession { fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::IClosable> { ::core::convert::TryInto::<super::super::Foundation::IClosable>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for ExtendedExecutionSession {} unsafe impl ::core::marker::Sync for ExtendedExecutionSession {} #[repr(transparent)] #[doc(hidden)] pub struct IExtendedExecutionRevokedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IExtendedExecutionRevokedEventArgs { type Vtable = IExtendedExecutionRevokedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbfbc9f16_63b5_4c0b_aad6_828af5373ec3); } #[repr(C)] #[doc(hidden)] pub struct IExtendedExecutionRevokedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ExtendedExecutionRevokedReason) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IExtendedExecutionSession(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IExtendedExecutionSession { type Vtable = IExtendedExecutionSession_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaf908a2d_118b_48f1_9308_0c4fc41e200f); } #[repr(C)] #[doc(hidden)] pub struct IExtendedExecutionSession_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ExtendedExecutionReason) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ExtendedExecutionReason) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, );
use rmps; use rocksdb::{Error, DB}; use std::boxed::Box; use std::collections::HashMap; use std::option::Option; #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ColumnDataType { Int(String), Text(String), } impl ColumnDataType { pub fn get_name(&self) -> &String { match self { ColumnDataType::Int(name) => name, ColumnDataType::Text(name) => name, } } } #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ColumnType { PrimaryKey(ColumnDataType), Nullable(ColumnDataType), NonNullable(ColumnDataType), } impl ColumnType { pub fn get_name(&self) -> &String { match self { ColumnType::PrimaryKey(data) => data.get_name(), ColumnType::Nullable(data) => data.get_name(), ColumnType::NonNullable(data) => data.get_name(), } } pub fn get_inner(&self) -> ColumnDataType { match self { ColumnType::PrimaryKey(data) => data.clone(), ColumnType::Nullable(data) => data.clone(), ColumnType::NonNullable(data) => data.clone(), } } } #[derive(Serialize, Deserialize, Debug)] pub struct TableBuilder { name: String, columns: Vec<ColumnType>, } impl TableBuilder { pub fn new(name: String) -> Self { TableBuilder { name, columns: Vec::new(), } } pub fn build_table(self, db: &DB) -> Table { let mut column_map: HashMap<String, i32> = HashMap::new(); let mut i = 0i32; let columns = self.columns; for col in columns.as_slice() { column_map.insert(col.get_name().to_owned(), i); i += 1; } let table = Table { name: self.name, column_map, columns, }; create_table(db, &table).unwrap(); table } pub fn set_columns(mut self, columns: Vec<ColumnType>) -> Self { self.columns.extend_from_slice(columns.as_slice()); self } } #[derive(Serialize, Deserialize, Debug)] pub struct Table { name: String, column_map: HashMap<String, i32>, columns: Vec<ColumnType>, } /// table name :: column name :: primary key value pub const COLUMN_KEY_NUM_COMPONENTS: u32 = 3; pub struct InsertStatement<'a> { table: &'a Table, i: i32, columns: Vec<Vec<u8>>, } pub trait VecSerializer { fn write_msgpack_in_vec(&self, buf: &mut Vec<u8>) -> Option<()>; fn check_declared_type(&self, declared_type: &ColumnType) -> bool; } impl VecSerializer for i64 { fn write_msgpack_in_vec(&self, buf: &mut Vec<u8>) -> Option<()> { match rmp::encode::write_sint(buf, *self) { Err(_) => None, _ => Some(()), } } fn check_declared_type(&self, declared_type: &ColumnType) -> bool { match declared_type.get_inner() { ColumnDataType::Int(_) => true, _ => false, } } } pub trait InsertError {} impl InsertError for rocksdb::Error {} #[derive(Debug)] pub struct ConsistencyError {} impl InsertError for ConsistencyError {} impl InsertError for std::io::Error {} impl std::fmt::Debug for std::boxed::Box<dyn InsertError> { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "write error") } } impl<'a> InsertStatement<'a> { pub fn set_kv<T: VecSerializer>(&mut self, key: &String, value: T) -> Option<&mut Self> { self.i = -1i32; let i: usize = *self.table.column_map.get(key)? as usize; if let Some(buf) = self.columns.get_mut(i) { value.write_msgpack_in_vec(buf)?; return Some(self); } None } pub fn set_next<T: VecSerializer>(&mut self, value: T) -> Option<&mut Self> { let i: usize = self.i as usize; self.i = self.i + 1; if let Some(buf) = self.columns.get_mut(i) { value.write_msgpack_in_vec(buf)?; return Some(self); } None } pub fn execute(&mut self, db: &DB) -> Result<(), Box<InsertError>> { let mut primary_keys: Vec<usize> = Vec::new(); { // count primary key number // nullable columns will be filled with msgpack nil; // other columns must be filled by user let mut i = 0; for v in self.columns.iter_mut() { if v.len() == 0 { match self.table.columns[i] { ColumnType::Nullable(_) => match rmp::encode::write_nil(v) { Ok(_) => {} Err(error_from_rocks) => return Err(Box::new(error_from_rocks)), }, _ => return Err(Box::new(ConsistencyError {})), }; } match self.table.columns[i] { ColumnType::PrimaryKey(_) => primary_keys.push(i), _ => {} }; i += 1; } } if primary_keys.len() == 0 { return Err(Box::new(ConsistencyError {})); } let mut pkey_component = Vec::<u8>::new(); rmp::encode::write_array_len(&mut pkey_component, primary_keys.len() as u32).unwrap(); for pk in primary_keys.iter() { pkey_component.extend_from_slice(self.columns[*pk].as_slice()); } { // fill in fields into storage engine let mut i = 0; for v in self.columns.iter_mut() { let column_name = self.table.columns[i].get_name(); let mut key = Vec::<u8>::new(); rmp::encode::write_array_len(&mut key, COLUMN_KEY_NUM_COMPONENTS).unwrap(); rmp::encode::write_str(&mut key, self.table.name.as_str()).unwrap(); rmp::encode::write_str(&mut key, column_name.as_str()).unwrap(); key.extend_from_slice(pkey_component.as_slice()); match db.put(key.as_slice(), v.as_slice()) { Ok(_) => {} Err(e) => return Err(Box::new(e)), } i += 1; } } return Ok(()); } } impl Table { pub fn table_key(&self) -> Vec<u8> { rmps::to_vec(&(".table", self.name.as_str())).unwrap() } pub fn table_value(&self) -> Vec<u8> { rmps::to_vec(&self).unwrap() } pub fn insert_into(&self) -> InsertStatement { let mut columns: Vec<Vec<u8>> = Vec::new(); columns.resize_with(self.columns.len(), Vec::new); InsertStatement { table: &self, i: 0i32, columns, } } } pub fn create_table(db: &DB, table: &Table) -> Result<(), Error> { db.put(table.table_key().as_slice(), table.table_value().as_slice()) } #[cfg(test)] mod tests { use super::{Table, TableBuilder, COLUMN_KEY_NUM_COMPONENTS}; use rmps; use rocksdb::DB; use std::borrow::Borrow; use tempdir::TempDir; use super::{ColumnDataType, ColumnType}; use std::collections::HashMap; #[test] fn test_msgpack_nested_array() { let output = rmps::to_vec(&(1, 2, (3, 4), 5)).unwrap(); // [0]: len 4 // [1]: 1 // [2]: 2 // [3]: len 2 assert_eq!(output[0], 0x94); assert_eq!(output[3], 0x92); } #[test] fn test_schema_key() { assert_eq!( Table { name: "User".to_owned(), column_map: HashMap::new(), columns: Vec::new(), } .table_key()[0], 0x92 ); } #[test] fn test_number_serialization_consistency() { assert_eq!(rmps::to_vec(&42).unwrap(), rmps::to_vec(&42u8).unwrap()); assert_eq!(rmps::to_vec(&42).unwrap(), rmps::to_vec(&42u16).unwrap()); assert_eq!(rmps::to_vec(&42).unwrap(), rmps::to_vec(&42u32).unwrap()); assert_eq!(rmps::to_vec(&42).unwrap(), rmps::to_vec(&42u64).unwrap()); } #[test] fn test_create_table_empty() { if let Ok(tmp_dir) = TempDir::new("") { let db = DB::open_default(tmp_dir.path().to_str().unwrap()).unwrap(); let table = TableBuilder::new("User".to_owned()).build_table(&db); let reply = db.get(table.table_key().as_slice()).unwrap().unwrap(); assert_eq!(reply.to_vec(), table.table_value()); } } #[test] fn test_create_table_ints() { if let Ok(tmp_dir) = TempDir::new("") { let db: DB = DB::open_default(tmp_dir.path().to_str().unwrap()).unwrap(); let table = TableBuilder::new("User".to_owned()) .set_columns(vec![ColumnType::PrimaryKey(ColumnDataType::Int( "id".to_owned(), ))]) .build_table(&db); table .insert_into() .set_kv(&"id".to_owned(), 1i64) .unwrap() .execute(&db) .unwrap(); { let mut key_prefix = Vec::<u8>::new(); rmp::encode::write_array_len(&mut key_prefix, COLUMN_KEY_NUM_COMPONENTS).unwrap(); rmp::encode::write_str(&mut key_prefix, "User").unwrap(); rmp::encode::write_str(&mut key_prefix, "id").unwrap(); let iter = db.prefix_iterator(key_prefix.as_slice()); for (key, value) in iter { let decoded_key: (String, String, (i64,)) = rmps::decode::from_slice(key.borrow()).unwrap(); let decoded_value: i64 = rmps::decode::from_slice(value.borrow()).unwrap(); println!("Saw {:?} {:?}", decoded_key, decoded_value); } } table .insert_into() .set_next(1i64) .unwrap() .execute(&db) .unwrap(); table .insert_into() .execute(&db) .expect_err("the column is not filled"); let reply = db.get(table.table_key().as_slice()).unwrap().unwrap(); assert_eq!(reply.to_vec(), table.table_value()); } } }
use sdl2; use sdl2::controller::Button; use sdl2::event::{Event, EventType as SdlEventType}; use sdl2::keyboard::Keycode; use sdl2::mouse::{MouseButton as SdlMouseButton, MouseUtil}; use sdl2::EventPump; use sdl2::EventSubsystem; use sdl2::GameControllerSubsystem; use sdl2::Sdl; use utilities::prelude::*; use std::ops::Deref; use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard}; use super::controller::Controller; use super::mousebutton::MouseButton; #[derive(Debug)] pub enum PresentationEventType { // mouse events MouseMotion(u32, u32), MouseButtonDown(MouseButton), MouseButtonUp(MouseButton), MouseWheel(), // keyboard events KeyDown(Keycode), KeyUp(Keycode), // controller events ControllerAxis(Arc<RwLock<Controller>>), ControllerButtonDown(Button), ControllerButtonUp(Button), ControllerAdded(Arc<RwLock<Controller>>), ControllerRemoved(Arc<RwLock<Controller>>), } pub struct EventSystem { event_pump: RwLock<EventPump>, mouse: Mutex<MouseUtil>, controller_subsystem: Mutex<GameControllerSubsystem>, event_subsystem: Mutex<EventSubsystem>, controller_axis_deadzone: RwLock<f32>, selected_controller: RwLock<Option<Arc<RwLock<Controller>>>>, connected_controllers: RwLock<Vec<Arc<RwLock<Controller>>>>, event_callback: RwLock<Box<dyn Fn(PresentationEventType) -> VerboseResult<()> + Send + Sync>>, } impl EventSystem { pub fn new(sdl2_context: &Sdl) -> VerboseResult<EventSystem> { let event_system = EventSystem { event_pump: RwLock::new(sdl2_context.event_pump()?), mouse: Mutex::new(sdl2_context.mouse()), controller_subsystem: Mutex::new(sdl2_context.game_controller()?), event_subsystem: Mutex::new(sdl2_context.event()?), controller_axis_deadzone: RwLock::new(0.25), selected_controller: RwLock::new(None), connected_controllers: RwLock::new(Vec::new()), event_callback: RwLock::new(Box::new(move |_| Ok(()))), }; event_system.disable_mouse()?; event_system.disable_keyboard()?; event_system.disable_controller()?; Ok(event_system) } pub fn set_callback<F>(&self, f: F) -> VerboseResult<()> where F: Fn(PresentationEventType) -> VerboseResult<()> + 'static + Send + Sync, { *self.event_callback.write()? = Box::new(f); Ok(()) } pub fn enable_mouse(&self) -> VerboseResult<()> { let mut event_pump = self.event_pump.write()?; event_pump.enable_event(SdlEventType::MouseMotion); event_pump.enable_event(SdlEventType::MouseButtonDown); event_pump.enable_event(SdlEventType::MouseButtonUp); self.mouse.lock()?.show_cursor(true); Ok(()) } pub fn disable_mouse(&self) -> VerboseResult<()> { let mut event_pump = self.event_pump.write()?; event_pump.disable_event(SdlEventType::MouseMotion); event_pump.disable_event(SdlEventType::MouseButtonDown); event_pump.disable_event(SdlEventType::MouseButtonUp); self.mouse.lock()?.show_cursor(false); Ok(()) } pub fn enable_keyboard(&self) -> VerboseResult<()> { let mut event_pump = self.event_pump.write()?; event_pump.enable_event(SdlEventType::KeyUp); event_pump.enable_event(SdlEventType::KeyDown); Ok(()) } pub fn disable_keyboard(&self) -> VerboseResult<()> { let mut event_pump = self.event_pump.write()?; event_pump.disable_event(SdlEventType::KeyUp); event_pump.disable_event(SdlEventType::KeyDown); Ok(()) } pub fn enable_controller(&self) -> VerboseResult<()> { let mut event_pump = self.event_pump.write()?; event_pump.enable_event(SdlEventType::ControllerAxisMotion); event_pump.enable_event(SdlEventType::ControllerButtonDown); event_pump.enable_event(SdlEventType::ControllerButtonUp); Ok(()) } pub fn disable_controller(&self) -> VerboseResult<()> { let mut event_pump = self.event_pump.write()?; event_pump.disable_event(SdlEventType::ControllerAxisMotion); event_pump.disable_event(SdlEventType::ControllerButtonDown); event_pump.disable_event(SdlEventType::ControllerButtonUp); Ok(()) } pub fn set_controller_axis_deadzone(&self, deadzone: f32) -> VerboseResult<()> { *self.controller_axis_deadzone.write()? = deadzone; Ok(()) } pub fn quit(&self) -> VerboseResult<()> { Ok(self .event_subsystem .lock()? .push_event(Event::Quit { timestamp: 0 })?) } pub fn poll_events(&self) -> VerboseResult<bool> { let mut controller_axis_changed = false; let mut event_pump = self.event_pump.write()?; for event in event_pump.poll_iter() { match event { Event::Quit { .. } => return Ok(false), // ----------------- Mouse Events --------------------- Event::MouseMotion { x, y, .. } => { self.event_callback.read()?(PresentationEventType::MouseMotion( x as u32, y as u32, ))?; } Event::MouseButtonDown { mouse_btn, .. } => { let mouse_button = match mouse_btn { SdlMouseButton::Left => MouseButton::Left, SdlMouseButton::Right => MouseButton::Right, SdlMouseButton::Middle => MouseButton::Middle, SdlMouseButton::X1 => MouseButton::Forward, SdlMouseButton::X2 => MouseButton::Backward, SdlMouseButton::Unknown => continue, }; self.event_callback.read()?(PresentationEventType::MouseButtonDown( mouse_button, ))?; } Event::MouseButtonUp { mouse_btn, .. } => { let mouse_button = match mouse_btn { SdlMouseButton::Left => MouseButton::Left, SdlMouseButton::Right => MouseButton::Right, SdlMouseButton::Middle => MouseButton::Middle, SdlMouseButton::X1 => MouseButton::Forward, SdlMouseButton::X2 => MouseButton::Backward, SdlMouseButton::Unknown => continue, }; self.event_callback.read()?(PresentationEventType::MouseButtonUp( mouse_button, ))?; } Event::MouseWheel { .. } => { println!("Mouse Wheel event is currently not implemented!"); } // ------------------- Key Events --------------------- Event::KeyDown { keycode, repeat, .. } => { if repeat { continue; } if let Some(keycode) = keycode { self.event_callback.read()?(PresentationEventType::KeyDown(keycode))?; } } Event::KeyUp { keycode, repeat, .. } => { if repeat { continue; } if let Some(keycode) = keycode { self.event_callback.read()?(PresentationEventType::KeyUp(keycode))?; } } // --------------- Controller Events ------------------- Event::ControllerDeviceAdded { which, .. } => { if let Ok(controller) = Controller::new( self.controller_subsystem.lock()?.deref(), which as u32, self.controller_axis_deadzone.read()?.clone(), ) { let controller = { let mut connected_controllers = self.connected_controllers.write()?; let mut selected_controller = self.selected_controller.write()?; let arc_controller = Arc::new(RwLock::new(controller)); connected_controllers.push(arc_controller.clone()); if selected_controller.is_none() { *selected_controller = Some(arc_controller.clone()); } arc_controller }; self.event_callback.read()?(PresentationEventType::ControllerAdded( controller, ))?; } } Event::ControllerDeviceRemoved { which, .. } => { let removed_controller = { let mut selected_controller = self.selected_controller.write()?; if selected_controller.is_some() { // unwrap is save since we just tested for `is_some()` if selected_controller.as_ref().unwrap().read()?.id() == which { *selected_controller = None; } } let mut connected_controllers = self.connected_controllers.write()?; let mut remove_index = 0; for (i, controller_cell) in connected_controllers.iter().enumerate() { let controller = controller_cell.read()?; if controller.id() == which { remove_index = i; break; } } let removed_controller = connected_controllers.swap_remove(remove_index); // if we removed the selected controller, take the controller at the first position if possible if selected_controller.is_none() && !connected_controllers.is_empty() { *selected_controller = Some(connected_controllers[0].clone()); } removed_controller }; self.event_callback.read()?(PresentationEventType::ControllerRemoved( removed_controller, ))?; } // maybe make use of `which`, for support of multiple controllers Event::ControllerButtonDown { button, which, .. } => { // only call back if the selected controller pressed a button match self.selected_controller.read()?.as_ref() { Some(selected_controller) => { if selected_controller.read()?.id() != which { continue; } } None => continue, } self.event_callback.read()?(PresentationEventType::ControllerButtonDown( button, ))?; } // maybe make use of `which`, for support of multiple controllers Event::ControllerButtonUp { button, which, .. } => { // only call back if the selected controller released a button match self.selected_controller.read()?.as_ref() { Some(selected_controller) => { if selected_controller.read()?.id() != which { continue; } } None => continue, } self.event_callback.read()?(PresentationEventType::ControllerButtonUp(button))?; } Event::ControllerAxisMotion { axis, value, which, .. } => { let mut selected_controller = self.selected_controller.write()?; if let Some(controller) = selected_controller.as_mut() { let mut controller = controller.write()?; // only update axis, when selected controller made the change if controller.id() != which { continue; } // 1 / 32768 = 0,000030518 let normalized = value as f32 * 0.000_030_518; match axis { sdl2::controller::Axis::LeftX => { controller.set_left_x(normalized); } sdl2::controller::Axis::RightX => { controller.set_right_x(normalized); } sdl2::controller::Axis::LeftY => { controller.set_left_y(-normalized); } sdl2::controller::Axis::RightY => { controller.set_right_y(normalized); } sdl2::controller::Axis::TriggerLeft => { controller.set_left_trigger(normalized); } sdl2::controller::Axis::TriggerRight => { controller.set_right_trigger(normalized); } } controller_axis_changed = true; } } _ => (), } } if controller_axis_changed { if let Some(controller) = self.selected_controller.read()?.as_ref() { self.event_callback.read()?(PresentationEventType::ControllerAxis( controller.clone(), ))?; } } Ok(true) } pub fn controllers(&self) -> VerboseResult<RwLockReadGuard<'_, Vec<Arc<RwLock<Controller>>>>> { Ok(self.connected_controllers.read()?) } pub fn active_controller(&self) -> VerboseResult<Option<Arc<RwLock<Controller>>>> { Ok(self.selected_controller.read()?.clone()) } pub fn set_active_controller(&self, controller: &Arc<RwLock<Controller>>) -> VerboseResult<()> { if let Some(res) = self .connected_controllers .read()? .iter() .find(|c| Arc::ptr_eq(c, controller)) { *self.selected_controller.write()? = Some(res.clone()); } Ok(()) } } unsafe impl Send for EventSystem {} unsafe impl Sync for EventSystem {}
use crate::common::{ListenerId, NetError, NetProtocol, Port, SocketAddress, SocketId}; // Socket events /// An event that is sent whenever a socket should be opened /// The `port` field must be specified when using UDP #[derive(Debug, Clone)] pub struct OpenSocket { pub new_id: SocketId, pub remote_address: SocketAddress, pub protocol: NetProtocol, pub port: Option<Port>, } /// An event that is sent whenever a socket is opened (connected) #[derive(Debug, Clone)] pub struct SocketOpened { pub id: SocketId, } /// An event that is sent whenever a socket should send data #[derive(Debug, Clone)] pub struct SendSocket { pub id: SocketId, pub tx_data: Vec<u8>, } /// An event that is sent whenever a socket sent data #[derive(Debug, Clone)] pub struct SocketSent { pub id: SocketId, pub len: usize, } /// An event that is sent whenever a socket receives data #[derive(Debug, Clone)] pub struct SocketReceive { pub id: SocketId, pub rx_data: Vec<u8>, } /// An event that is sent whenever a socket has an error #[derive(Debug, Clone)] pub struct SocketError { pub id: SocketId, pub err: NetError, } /// An event that is sent whenever a socket should be closed #[derive(Debug, Clone)] pub struct CloseSocket { pub id: SocketId, } /// An event that is sent whenever a socket is closed #[derive(Debug, Clone)] pub struct SocketClosed { pub id: SocketId, } // Listener events /// An event that is sent whenever a listener should be created #[derive(Debug, Clone)] pub struct CreateListener { pub new_id: ListenerId, pub port: Port, pub protocol: NetProtocol, } /// An event that is sent whenever a listener is opened #[derive(Debug, Clone)] pub struct ListenerCreated { pub id: ListenerId, } /* /// An event that is sent whenever a listener receives a connection request #[derive(Debug, Clone)] pub struct ListenerRequest { pub id: ListenerId, pub remote_addr: SocketAddress } /// An event that is sent whenever a listener should respond to a connection request #[derive(Debug, Clone)] pub struct HandleListener { pub id: ListenerId, pub remote_addr: SocketAddress, pub accept: bool } */ /// An event that is sent whenever a listener creates a connection #[derive(Debug, Clone)] pub struct ListenerConnected { pub id: ListenerId, pub socket_id: SocketId, pub socket_address: SocketAddress, } /// An event that is sent whenever a listener has an error #[derive(Debug, Clone)] pub struct ListenerError { pub id: ListenerId, pub err: NetError, } /// An event that is sent whenever a listener should be closed #[derive(Debug, Clone)] pub struct CloseListener { pub id: ListenerId, } /// An event that is sent whenever a listener is closed #[derive(Debug, Clone)] pub struct ListenerClosed { pub id: ListenerId, }
#[doc = "Reader of register IC"] pub type R = crate::R<u32, super::IC>; #[doc = "Writer for register IC"] pub type W = crate::W<u32, super::IC>; #[doc = "Register IC `reset()`'s with value 0"] impl crate::ResetValue for super::IC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `RTCALT0`"] pub type RTCALT0_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RTCALT0`"] pub struct RTCALT0_W<'a> { w: &'a mut W, } impl<'a> RTCALT0_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `LOWBAT`"] pub type LOWBAT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `LOWBAT`"] pub struct LOWBAT_W<'a> { w: &'a mut W, } impl<'a> LOWBAT_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `EXTW`"] pub type EXTW_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EXTW`"] pub struct EXTW_W<'a> { w: &'a mut W, } impl<'a> EXTW_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `WC`"] pub type WC_R = crate::R<bool, bool>; #[doc = "Write proxy for field `WC`"] pub struct WC_W<'a> { w: &'a mut W, } impl<'a> WC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } impl R { #[doc = "Bit 0 - RTC Alert0 Masked Interrupt Clear"] #[inline(always)] pub fn rtcalt0(&self) -> RTCALT0_R { RTCALT0_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 2 - Low Battery Voltage Interrupt Clear"] #[inline(always)] pub fn lowbat(&self) -> LOWBAT_R { LOWBAT_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - External Wake-Up Interrupt Clear"] #[inline(always)] pub fn extw(&self) -> EXTW_R { EXTW_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - Write Complete/Capable Interrupt Clear"] #[inline(always)] pub fn wc(&self) -> WC_R { WC_R::new(((self.bits >> 4) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - RTC Alert0 Masked Interrupt Clear"] #[inline(always)] pub fn rtcalt0(&mut self) -> RTCALT0_W { RTCALT0_W { w: self } } #[doc = "Bit 2 - Low Battery Voltage Interrupt Clear"] #[inline(always)] pub fn lowbat(&mut self) -> LOWBAT_W { LOWBAT_W { w: self } } #[doc = "Bit 3 - External Wake-Up Interrupt Clear"] #[inline(always)] pub fn extw(&mut self) -> EXTW_W { EXTW_W { w: self } } #[doc = "Bit 4 - Write Complete/Capable Interrupt Clear"] #[inline(always)] pub fn wc(&mut self) -> WC_W { WC_W { w: self } } }
#[doc = r"Value read from the register"] pub struct R { bits: u8, } #[doc = r"Value to write to the register"] pub struct W { bits: u8, } impl super::RXCSRH6 { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u8 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct USB_RXCSRH6_INCOMPRXR { bits: bool, } impl USB_RXCSRH6_INCOMPRXR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_RXCSRH6_INCOMPRXW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH6_INCOMPRXW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u8) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH6_DTR { bits: bool, } impl USB_RXCSRH6_DTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_RXCSRH6_DTW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH6_DTW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u8) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH6_DTWER { bits: bool, } impl USB_RXCSRH6_DTWER { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_RXCSRH6_DTWEW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH6_DTWEW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u8) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH6_DMAMODR { bits: bool, } impl USB_RXCSRH6_DMAMODR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_RXCSRH6_DMAMODW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH6_DMAMODW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 3); self.w.bits |= ((value as u8) & 1) << 3; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH6_PIDERRR { bits: bool, } impl USB_RXCSRH6_PIDERRR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_RXCSRH6_PIDERRW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH6_PIDERRW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 4); self.w.bits |= ((value as u8) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH6_DMAENR { bits: bool, } impl USB_RXCSRH6_DMAENR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_RXCSRH6_DMAENW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH6_DMAENW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 5); self.w.bits |= ((value as u8) & 1) << 5; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH6_AUTORQR { bits: bool, } impl USB_RXCSRH6_AUTORQR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_RXCSRH6_AUTORQW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH6_AUTORQW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 6); self.w.bits |= ((value as u8) & 1) << 6; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH6_AUTOCLR { bits: bool, } impl USB_RXCSRH6_AUTOCLR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_RXCSRH6_AUTOCLW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH6_AUTOCLW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 7); self.w.bits |= ((value as u8) & 1) << 7; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH6_DISNYETR { bits: bool, } impl USB_RXCSRH6_DISNYETR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_RXCSRH6_DISNYETW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH6_DISNYETW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 4); self.w.bits |= ((value as u8) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct USB_RXCSRH6_ISOR { bits: bool, } impl USB_RXCSRH6_ISOR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_RXCSRH6_ISOW<'a> { w: &'a mut W, } impl<'a> _USB_RXCSRH6_ISOW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 6); self.w.bits |= ((value as u8) & 1) << 6; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } #[doc = "Bit 0 - Incomplete RX Transmission Status"] #[inline(always)] pub fn usb_rxcsrh6_incomprx(&self) -> USB_RXCSRH6_INCOMPRXR { let bits = ((self.bits >> 0) & 1) != 0; USB_RXCSRH6_INCOMPRXR { bits } } #[doc = "Bit 1 - Data Toggle"] #[inline(always)] pub fn usb_rxcsrh6_dt(&self) -> USB_RXCSRH6_DTR { let bits = ((self.bits >> 1) & 1) != 0; USB_RXCSRH6_DTR { bits } } #[doc = "Bit 2 - Data Toggle Write Enable"] #[inline(always)] pub fn usb_rxcsrh6_dtwe(&self) -> USB_RXCSRH6_DTWER { let bits = ((self.bits >> 2) & 1) != 0; USB_RXCSRH6_DTWER { bits } } #[doc = "Bit 3 - DMA Request Mode"] #[inline(always)] pub fn usb_rxcsrh6_dmamod(&self) -> USB_RXCSRH6_DMAMODR { let bits = ((self.bits >> 3) & 1) != 0; USB_RXCSRH6_DMAMODR { bits } } #[doc = "Bit 4 - PID Error"] #[inline(always)] pub fn usb_rxcsrh6_piderr(&self) -> USB_RXCSRH6_PIDERRR { let bits = ((self.bits >> 4) & 1) != 0; USB_RXCSRH6_PIDERRR { bits } } #[doc = "Bit 5 - DMA Request Enable"] #[inline(always)] pub fn usb_rxcsrh6_dmaen(&self) -> USB_RXCSRH6_DMAENR { let bits = ((self.bits >> 5) & 1) != 0; USB_RXCSRH6_DMAENR { bits } } #[doc = "Bit 6 - Auto Request"] #[inline(always)] pub fn usb_rxcsrh6_autorq(&self) -> USB_RXCSRH6_AUTORQR { let bits = ((self.bits >> 6) & 1) != 0; USB_RXCSRH6_AUTORQR { bits } } #[doc = "Bit 7 - Auto Clear"] #[inline(always)] pub fn usb_rxcsrh6_autocl(&self) -> USB_RXCSRH6_AUTOCLR { let bits = ((self.bits >> 7) & 1) != 0; USB_RXCSRH6_AUTOCLR { bits } } #[doc = "Bit 4 - Disable NYET"] #[inline(always)] pub fn usb_rxcsrh6_disnyet(&self) -> USB_RXCSRH6_DISNYETR { let bits = ((self.bits >> 4) & 1) != 0; USB_RXCSRH6_DISNYETR { bits } } #[doc = "Bit 6 - Isochronous Transfers"] #[inline(always)] pub fn usb_rxcsrh6_iso(&self) -> USB_RXCSRH6_ISOR { let bits = ((self.bits >> 6) & 1) != 0; USB_RXCSRH6_ISOR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u8) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Incomplete RX Transmission Status"] #[inline(always)] pub fn usb_rxcsrh6_incomprx(&mut self) -> _USB_RXCSRH6_INCOMPRXW { _USB_RXCSRH6_INCOMPRXW { w: self } } #[doc = "Bit 1 - Data Toggle"] #[inline(always)] pub fn usb_rxcsrh6_dt(&mut self) -> _USB_RXCSRH6_DTW { _USB_RXCSRH6_DTW { w: self } } #[doc = "Bit 2 - Data Toggle Write Enable"] #[inline(always)] pub fn usb_rxcsrh6_dtwe(&mut self) -> _USB_RXCSRH6_DTWEW { _USB_RXCSRH6_DTWEW { w: self } } #[doc = "Bit 3 - DMA Request Mode"] #[inline(always)] pub fn usb_rxcsrh6_dmamod(&mut self) -> _USB_RXCSRH6_DMAMODW { _USB_RXCSRH6_DMAMODW { w: self } } #[doc = "Bit 4 - PID Error"] #[inline(always)] pub fn usb_rxcsrh6_piderr(&mut self) -> _USB_RXCSRH6_PIDERRW { _USB_RXCSRH6_PIDERRW { w: self } } #[doc = "Bit 5 - DMA Request Enable"] #[inline(always)] pub fn usb_rxcsrh6_dmaen(&mut self) -> _USB_RXCSRH6_DMAENW { _USB_RXCSRH6_DMAENW { w: self } } #[doc = "Bit 6 - Auto Request"] #[inline(always)] pub fn usb_rxcsrh6_autorq(&mut self) -> _USB_RXCSRH6_AUTORQW { _USB_RXCSRH6_AUTORQW { w: self } } #[doc = "Bit 7 - Auto Clear"] #[inline(always)] pub fn usb_rxcsrh6_autocl(&mut self) -> _USB_RXCSRH6_AUTOCLW { _USB_RXCSRH6_AUTOCLW { w: self } } #[doc = "Bit 4 - Disable NYET"] #[inline(always)] pub fn usb_rxcsrh6_disnyet(&mut self) -> _USB_RXCSRH6_DISNYETW { _USB_RXCSRH6_DISNYETW { w: self } } #[doc = "Bit 6 - Isochronous Transfers"] #[inline(always)] pub fn usb_rxcsrh6_iso(&mut self) -> _USB_RXCSRH6_ISOW { _USB_RXCSRH6_ISOW { w: self } } }
use std::fmt::Display; use data_types::{CompactionLevel, ParquetFile, Timestamp}; use crate::{ components::split_or_compact::start_level_files_to_split::{ merge_small_l0_chains, split_into_chains, }, RoundInfo, }; use super::DivideInitial; #[derive(Debug, Default)] pub struct MultipleBranchesDivideInitial; impl MultipleBranchesDivideInitial { pub fn new() -> Self { Self } } impl Display for MultipleBranchesDivideInitial { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "multiple_branches") } } impl DivideInitial for MultipleBranchesDivideInitial { fn divide( &self, files: Vec<ParquetFile>, round_info: RoundInfo, ) -> (Vec<Vec<ParquetFile>>, Vec<ParquetFile>) { let mut more_for_later = vec![]; match round_info { RoundInfo::ManySmallFiles { start_level, max_num_files_to_group, max_total_file_size_to_group, } => { // Files must be sorted by `max_l0_created_at` when there are overlaps to resolve. // If the `start_level` is greater than 0, there cannot be overlaps within the level, // so sorting by `max_l0_created_at` is not necessary (however, sorting by `min_time` // is needed to avoid introducing overlaps within their levels). When the `start_level` // is 0, we have to sort by `max_l0_created_at` if a chain of overlaps is too big for // a single compaction. // // See tests many_l0_files_different_created_order and many_l1_files_different_created_order for examples let start_level_files = files .into_iter() .filter(|f| f.compaction_level == start_level) .collect::<Vec<_>>(); let mut branches = Vec::with_capacity(start_level_files.len()); let mut chains = Vec::with_capacity(start_level_files.len()); if start_level == CompactionLevel::Initial { // L0 files can be highly overlapping, requiring 'vertical splitting' (see high_l0_overlap_split). // Achieving `vertical splitting` requires we tweak the grouping here for two reasons: // 1) Allow the large highly overlapped groups of L0s to remain in a single branch, so they trigger the split // 2) Prevent the output of a prior split from being grouped together to undo the previous veritacal split. // Both of these objectives need to consider the L0s as a chains of overlapping files. The chains are // each a set of L0s that overlap each other, but do not overlap the other chains. // Chains can be created based on min_time/max_time without regard for max_l0_created_at because there // are no overlaps between chains. let initial_chains = split_into_chains(start_level_files); // Reason 1) above - keep the large groups of L0s in a single branch to facilitate later splitting. for chain in initial_chains { let this_chain_bytes: usize = chain.iter().map(|f| f.file_size_bytes as usize).sum(); if this_chain_bytes > 2 * max_total_file_size_to_group { // This is a very large set of overlapping L0s, its needs vertical splitting, so keep the branch intact // to trigger the split. branches.push(chain); } else { chains.push(chain); } } // If the chains are smaller than the max compact size, combine them to get better compaction group sizes. // This combining of chains must happen based on max_l0_created_at (it can only join adjacent chains, when // sorted by max_l0_created_at). chains = merge_small_l0_chains(chains, max_total_file_size_to_group); } else { chains = vec![start_level_files]; } // Reason 2) above - ensure the grouping in branches doesn't undo the vertical splitting. // Assume we start with 30 files (A,B,C,...), that were each split into 3 files (A1, A2, A3, B1, ..). If we create branches // from sorting all files by max_l0_created_at we'd undo the vertical splitting (A1-A3 would get compacted back into one file). // Currently the contents of each chain is more like A1, B1, C1, so by grouping chains together we can preserve the previous // vertical splitting. for chain in chains { let start_level_files = order_files(chain, start_level); let capacity = start_level_files.len(); // Split L0s into many small groups, each has max_num_files_to_group but not exceed max_total_file_size_to_group // Collect files until either limit is reached let mut current_branch = Vec::with_capacity(capacity); let mut current_branch_size = 0; for f in start_level_files { if current_branch.len() == max_num_files_to_group || current_branch_size + f.file_size_bytes as usize > max_total_file_size_to_group { // panic if current_branch is empty if current_branch.is_empty() { panic!("Size of a file {} is larger than the max size limit to compact. Please adjust the settings. See ticket https://github.com/influxdata/idpe/issues/17209" , f.file_size_bytes); } if current_branch.len() == 1 { // Compacting a branch of 1 won't help us reduce the L0 file count. Put it on the ignore list. more_for_later.push(current_branch.pop().unwrap()); } else { branches.push(current_branch); } current_branch = Vec::with_capacity(capacity); current_branch_size = 0; } current_branch_size += f.file_size_bytes as usize; current_branch.push(f); } // push the last branch if !current_branch.is_empty() { if current_branch.len() == 1 { // Compacting a branch of 1 won't help us reduce the L0 file count. Put it on the ignore list. more_for_later.push(current_branch.pop().unwrap()); } else { branches.push(current_branch); } } } (branches, more_for_later) } RoundInfo::TargetLevel { .. } => (vec![files], more_for_later), RoundInfo::SimulatedLeadingEdge { max_num_files_to_group, max_total_file_size_to_group, } => { // There may be a lot of L0s, but we're going to keep it simple and just look at the first (few). let start_level = CompactionLevel::Initial; // Separate start_level_files (L0s) from target_level_files (L1), and `more_for_later` which is all the rest of the files (L2). // We'll then with the first L0 and see how many L1s it needs to drag into its compaction, and then look at the next L0 // and see how many L1s it needs, etc. We'll end up with 1 or more L0s, and whatever L1s they need to compact with. // When we can't add any more without getting "too big", we'll consider that our branch, and all remaining L0s, L1s & L2s // are returned as let (start_level_files, rest): (Vec<ParquetFile>, Vec<ParquetFile>) = files .into_iter() .partition(|f| f.compaction_level == start_level); let (mut target_level_files, mut more_for_later): ( Vec<ParquetFile>, Vec<ParquetFile>, ) = rest .into_iter() .partition(|f| f.compaction_level == start_level.next()); let mut start_level_files = order_files(start_level_files, start_level); let mut current_branch = Vec::with_capacity(start_level_files.len()); let mut current_branch_size = 0; let mut min_time = Timestamp::new(i64::MAX); let mut max_time = Timestamp::new(0); // Until we run out of L0s or return early with a branch to compact, keep adding L0s & their overlapping L1s to the current branch. while !start_level_files.is_empty() { let f = start_level_files.remove(0); // overlaps of this new file isn't enough - we must look for overlaps of this + all previously added L0s, because the result of // compacting them will be that whole time range. Therefore, we must include all L1s overlapping that entire time range. min_time = min_time.min(f.min_time); max_time = max_time.max(f.max_time); let (mut overlaps, remainder): (Vec<ParquetFile>, Vec<ParquetFile>) = target_level_files .into_iter() .partition(|f2| f2.overlaps_time_range(min_time, max_time)); target_level_files = remainder; if current_branch_size == 0 || // minimum 1 start level file (current_branch.len() + overlaps.len() < max_num_files_to_group && current_branch_size + f.size() < max_total_file_size_to_group) { // This L0 & its overlapping L1s fit in the current branch. current_branch_size += f.size(); current_branch.push(f); current_branch.append(&mut overlaps); } else { // This L0 & its overlapping L1s would make the current branch too big. // We're done - what we previously added to the branch will be compacted, everything else goes in more_for_later. more_for_later.push(f); more_for_later.append(&mut overlaps); more_for_later.append(&mut start_level_files); more_for_later.append(&mut target_level_files); return (vec![current_branch], more_for_later); } } (vec![current_branch], more_for_later) } } } } /// Return a sorted files of the given ones. /// The order is used to split the files and form the right groups of files to compact /// and deduplicate correctly to fewer and larger but same level files /// /// All given files are in the same given start_level. /// They will be sorted on their `max_l0_created_at` (then `min_time`) if the start_level is 0, /// otherwise on their `min_time` pub fn order_files(files: Vec<ParquetFile>, start_level: CompactionLevel) -> Vec<ParquetFile> { let mut files = files; if start_level == CompactionLevel::Initial { files.sort_by(|a, b| { if a.max_l0_created_at == b.max_l0_created_at { a.min_time.cmp(&b.min_time) } else { a.max_l0_created_at.cmp(&b.max_l0_created_at) } }) } else { files.sort_by(|a, b| a.min_time.cmp(&b.min_time)); } files } #[cfg(test)] mod tests { use data_types::CompactionLevel; use iox_tests::ParquetFileBuilder; use super::*; #[test] fn test_display() { assert_eq!( MultipleBranchesDivideInitial::new().to_string(), "multiple_branches" ); } #[test] fn test_divide_num_file() { let round_info = RoundInfo::ManySmallFiles { start_level: CompactionLevel::Initial, max_num_files_to_group: 2, max_total_file_size_to_group: 100, }; let divide = MultipleBranchesDivideInitial::new(); // empty input assert_eq!( divide.divide(vec![], round_info), (Vec::<Vec<_>>::new(), Vec::new()) ); // not empty let f1 = ParquetFileBuilder::new(1) .with_compaction_level(CompactionLevel::Initial) .with_max_l0_created_at(1) .build(); let f2 = ParquetFileBuilder::new(2) .with_compaction_level(CompactionLevel::Initial) .with_max_l0_created_at(5) .build(); let f3 = ParquetFileBuilder::new(3) .with_compaction_level(CompactionLevel::Initial) .with_max_l0_created_at(10) .build(); // files in random order of max_l0_created_at let files = vec![f2.clone(), f3.clone(), f1.clone()]; let (branches, more_for_later) = divide.divide(files, round_info); // output must be split into their max_l0_created_at assert_eq!(branches.len(), 1); assert_eq!(more_for_later.len(), 1); assert_eq!(branches[0], vec![f1, f2]); } #[test] #[should_panic( expected = "Size of a file 50 is larger than the max size limit to compact. Please adjust the settings" )] fn test_divide_size_limit_too_small() { let round_info = RoundInfo::ManySmallFiles { start_level: CompactionLevel::Initial, max_num_files_to_group: 10, max_total_file_size_to_group: 40, }; let divide = MultipleBranchesDivideInitial::new(); let f1 = ParquetFileBuilder::new(1) .with_compaction_level(CompactionLevel::Initial) .with_max_l0_created_at(1) .with_file_size_bytes(50) .build(); let f2 = ParquetFileBuilder::new(2) .with_compaction_level(CompactionLevel::Initial) .with_max_l0_created_at(5) .with_file_size_bytes(5) .build(); // files in random order of max_l0_created_at let files = vec![f2, f1]; // panic let (_branches, _more_for_later) = divide.divide(files, round_info); } #[test] fn test_divide_size_limit() { let round_info = RoundInfo::ManySmallFiles { start_level: CompactionLevel::Initial, max_num_files_to_group: 10, max_total_file_size_to_group: 100, }; let divide = MultipleBranchesDivideInitial::new(); let f1 = ParquetFileBuilder::new(1) .with_compaction_level(CompactionLevel::Initial) .with_max_l0_created_at(1) .with_file_size_bytes(90) .build(); let f2 = ParquetFileBuilder::new(2) .with_compaction_level(CompactionLevel::Initial) .with_max_l0_created_at(5) .with_file_size_bytes(20) .build(); let f3 = ParquetFileBuilder::new(3) .with_compaction_level(CompactionLevel::Initial) .with_max_l0_created_at(10) .with_file_size_bytes(30) .build(); // files in random order of max_l0_created_at let files = vec![f2.clone(), f3.clone(), f1.clone()]; let (branches, more_for_later) = divide.divide(files, round_info); // output must be split into their max_l0_created_at assert_eq!(branches.len(), 1); assert_eq!(more_for_later.len(), 1); assert_eq!(branches[0], vec![f2, f3]); } }
use std::io; use std::io::prelude::*; use std::str; use std::fmt; use std::net::{Ipv4Addr, TcpStream, UdpSocket}; use std::time::{Instant, Duration}; #[derive(Debug,PartialEq,Clone)] pub struct Board { pub ip: Ipv4Addr, pub mac: [u8; 6], } pub fn autodiscover() -> io::Result<Vec<Board>> { let mut boards: Vec<Board> = Vec::new(); let mut buf = [0u8; 128]; let socket = UdpSocket::bind(("0.0.0.0", 9090))?; socket.set_read_timeout(Some(Duration::from_millis(500)))?; let start = Instant::now(); while Instant::now().duration_since(start) < Duration::from_millis(2000) { match socket.recv(&mut buf) { Ok(_) => match Board::from_packet(&buf) { Some(board) => if !boards.contains(&board) { boards.push(board); }, None => continue, }, Err(e) => match e.kind() { io::ErrorKind::WouldBlock => continue, io::ErrorKind::TimedOut => continue, _ => return Err(e), }, } } Ok(boards) } impl Board { fn from_packet(buf: &[u8]) -> Option<Board> { if buf.len() < 18 { return None; } match str::from_utf8(&buf[0..8]) { Ok(s) => if s != "PORTFIRE" { return None; }, Err(_) => return None, } let ip = Ipv4Addr::new(buf[8], buf[9], buf[10], buf[11]); let mac = [buf[12], buf[13], buf[14], buf[15], buf[16], buf[17]]; Some(Board { ip: ip, mac: mac }) } fn txrx(&self, cmd: &[u8], buf: &mut [u8]) -> io::Result<usize> { let mut stream = TcpStream::connect((self.ip, 9090))?; stream.set_nodelay(true)?; stream.set_read_timeout(Some(Duration::from_millis(1500)))?; stream.set_write_timeout(Some(Duration::from_millis(100)))?; let _ = stream.write(cmd)?; stream.read(buf) } fn txrx_ok(&self, cmd: &[u8]) -> io::Result<()> { let mut buf = [0u8; 4]; self.txrx(cmd, &mut buf)?; if buf[0] == 'O' as u8 && buf[1] == 'K' as u8 { Ok(()) } else { Err(io::Error::new(io::ErrorKind::Other, "Invalid response")) } } pub fn ping(&self) -> io::Result<()> { let cmd = ['p' as u8]; self.txrx_ok(&cmd) } pub fn arm(&self) -> io::Result<()> { let cmd = ['a' as u8]; self.txrx_ok(&cmd) } pub fn disarm(&self) -> io::Result<()> { let cmd = ['d' as u8]; self.txrx_ok(&cmd) } pub fn fire(&self, channels: [u8; 3]) -> io::Result<()> { let cmd = ['f' as u8, channels[0], channels[1], channels[2]]; self.txrx_ok(&cmd) } pub fn fire_retry(&self, channels: [u8; 3]) { while let Err(_) = self.arm() { println!("ERROR: Retrying arming command to board {}", self.ip); } while let Err(_) = self.fire(channels) { println!("ERROR: Retrying firing command to board {}", self.ip); while let Err(_) = self.arm() {} } } pub fn bus_voltage(&self) -> io::Result<f32> { let mut buf = [0u8; 2]; let cmd = ['b' as u8]; self.txrx(&cmd, &mut buf)?; Ok((((buf[0] as u16) | ((buf[1] as u16)<<8)) as f32)/1000.0) } pub fn continuities(&self) -> io::Result<[u8; 31]> { let mut buf = [0u8; 31]; let cmd = ['c' as u8]; self.txrx(&cmd, &mut buf)?; Ok(buf) } } impl fmt::Display for Board { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Board {:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X} at {}", self.mac[0], self.mac[1], self.mac[2], self.mac[3], self.mac[4], self.mac[5], self.ip) } }
// Copyright (c) The diem-devtools Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 use crate::{ output::OutputFormat, reporter::Color, test_filter::{FilterMatch, TestFilterBuilder}, }; use anyhow::{anyhow, Context, Result}; use camino::{Utf8Path, Utf8PathBuf}; use duct::cmd; use once_cell::sync::OnceCell; use serde::{Deserialize, Serialize}; use std::{collections::BTreeMap, io, path::Path}; use termcolor::{BufferWriter, ColorSpec, NoColor, WriteColor}; // TODO: capture ignored and not-ignored tests /// Represents a test binary. /// /// Accepted as input to `TestList::new`. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub struct TestBinary { /// The test binary. pub binary: Utf8PathBuf, /// A unique identifier for this binary, typically the package + binary name defined in /// `Cargo.toml`. pub binary_id: String, /// The working directory that this test should be executed in. If None, the current directory /// will not be changed. pub cwd: Option<Utf8PathBuf>, } /// List of tests, gotten by executing a test binary with the `--list` command. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub struct TestList { /// Number of tests (including skipped and ignored) across all binaries. test_count: usize, test_binaries: BTreeMap<Utf8PathBuf, TestBinInfo>, // Values computed on first access. #[serde(skip)] skip_count: OnceCell<usize>, } /// Information about a test binary. #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub struct TestBinInfo { /// A unique identifier for this binary, typically the package + binary name defined in /// `Cargo.toml`. pub binary_id: String, /// Test names and other information. pub tests: BTreeMap<String, RustTestInfo>, /// The working directory that this test binary will be executed in. If None, the current directory /// will not be changed. pub cwd: Option<Utf8PathBuf>, } /// Information about a single Rust test. #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub struct RustTestInfo { /// Returns true if this test is marked ignored. /// /// Ignored tests, if run, are executed with the `--ignored` argument. pub ignored: bool, /// Whether the test matches the provided test filter. /// /// Only tests that match the filter are run. pub filter_match: FilterMatch, } impl TestList { /// Creates a new test list by running the given command and applying the specified filter. pub fn new( test_binaries: impl IntoIterator<Item = TestBinary>, filter: &TestFilterBuilder, ) -> Result<Self> { let mut test_count = 0; let test_binaries = test_binaries .into_iter() .map(|test_binary| { let (non_ignored, ignored) = test_binary.exec()?; let (bin, info) = Self::process_output( test_binary, filter, non_ignored.as_str(), ignored.as_str(), )?; test_count += info.tests.len(); Ok((bin, info)) }) .collect::<Result<BTreeMap<_, _>>>()?; Ok(Self { test_binaries, test_count, skip_count: OnceCell::new(), }) } /// Creates a new test list with the given binary names and outputs. pub fn new_with_outputs( test_bin_outputs: impl IntoIterator<Item = (TestBinary, impl AsRef<str>, impl AsRef<str>)>, filter: &TestFilterBuilder, ) -> Result<Self> { let mut test_count = 0; let test_binaries = test_bin_outputs .into_iter() .map(|(test_binary, non_ignored, ignored)| { let (bin, info) = Self::process_output( test_binary, filter, non_ignored.as_ref(), ignored.as_ref(), )?; test_count += info.tests.len(); Ok((bin, info)) }) .collect::<Result<BTreeMap<_, _>>>()?; Ok(Self { test_binaries, test_count, skip_count: OnceCell::new(), }) } /// Returns the total number of tests across all binaries. pub fn test_count(&self) -> usize { self.test_count } /// Returns the total number of skipped tests. pub fn skip_count(&self) -> usize { *self.skip_count.get_or_init(|| { self.iter_tests() .filter(|instance| !instance.info.filter_match.is_match()) .count() }) } /// Returns the total number of tests that aren't skipped. /// /// It is always the case that `run_count + skip_count == test_count`. pub fn run_count(&self) -> usize { self.test_count - self.skip_count() } /// Returns the total number of binaries that contain tests. pub fn binary_count(&self) -> usize { self.test_binaries.len() } /// Returns the tests for a given binary, or `None` if the binary wasn't in the list. pub fn get(&self, test_bin: impl AsRef<Utf8Path>) -> Option<&TestBinInfo> { self.test_binaries.get(test_bin.as_ref()) } /// Writes the list to stdout. pub fn write_to_stdout(&self, color: Color, output_format: OutputFormat) -> Result<()> { let stdout = BufferWriter::stdout(color.color_choice(atty::Stream::Stdout)); let mut buffer = stdout.buffer(); self.write(output_format, &mut buffer)?; stdout.print(&buffer).context("error writing output") } /// Outputs this list to the given writer. pub fn write(&self, output_format: OutputFormat, writer: impl WriteColor) -> Result<()> { match output_format { OutputFormat::Plain => self.write_plain(writer).context("error writing test list"), OutputFormat::Serializable(format) => format.to_writer(self, writer), } } /// Iterates over all the test binaries. pub fn iter(&self) -> impl Iterator<Item = (&Utf8Path, &TestBinInfo)> + '_ { self.test_binaries .iter() .map(|(path, info)| (path.as_path(), info)) } /// Iterates over the list of tests, returning the path and test name. pub fn iter_tests(&self) -> impl Iterator<Item = TestInstance<'_>> + '_ { self.test_binaries.iter().flat_map(|(test_bin, bin_info)| { bin_info.tests.iter().map(move |(name, info)| { TestInstance::new( name, test_bin, &bin_info.binary_id, info, bin_info.cwd.as_deref(), ) }) }) } /// Outputs this list as a string with the given format. pub fn to_string(&self, output_format: OutputFormat) -> Result<String> { // Ugh this sucks. String really should have an io::Write impl that errors on non-UTF8 text. let mut buf = NoColor::new(vec![]); self.write(output_format, &mut buf)?; Ok(String::from_utf8(buf.into_inner()).expect("buffer is valid UTF-8")) } // --- // Helper methods // --- fn process_output( test_binary: TestBinary, filter: &TestFilterBuilder, non_ignored: impl AsRef<str>, ignored: impl AsRef<str>, ) -> Result<(Utf8PathBuf, TestBinInfo)> { let mut tests = BTreeMap::new(); // Treat ignored and non-ignored as separate sets of single filters, so that partitioning // based on one doesn't affect the other. let mut non_ignored_filter = filter.build(&test_binary); for test_name in Self::parse(non_ignored.as_ref())? { tests.insert( test_name.into(), RustTestInfo { ignored: false, filter_match: non_ignored_filter.filter_match(&test_name, false), }, ); } let mut ignored_filter = filter.build(&test_binary); for test_name in Self::parse(ignored.as_ref())? { // TODO: catch dups tests.insert( test_name.into(), RustTestInfo { ignored: true, filter_match: ignored_filter.filter_match(&test_name, true), }, ); } let TestBinary { binary, cwd, binary_id, } = test_binary; Ok(( binary, TestBinInfo { binary_id, tests, cwd, }, )) } /// Parses the output of --list --format terse and returns a sorted list. fn parse(list_output: &str) -> Result<Vec<&'_ str>> { let mut list = Self::parse_impl(list_output).collect::<Result<Vec<_>>>()?; list.sort_unstable(); Ok(list) } fn parse_impl(list_output: &str) -> impl Iterator<Item = Result<&'_ str>> + '_ { // The output is in the form: // <test name>: test // <test name>: test // ... list_output.lines().map(move |line| { line.strip_suffix(": test").ok_or_else(|| { anyhow!( "line '{}' did not end with the string ': test', full output:\n{}", line, list_output ) }) }) } fn write_plain(&self, mut writer: impl WriteColor) -> io::Result<()> { let test_bin_spec = test_bin_spec(); let field_spec = Self::field_spec(); let test_name_spec = test_name_spec(); for (test_bin, info) in &self.test_binaries { writer.set_color(&test_bin_spec)?; write!(writer, "{}", test_bin)?; writer.reset()?; writeln!(writer, ":")?; if let Some(cwd) = &info.cwd { writer.set_color(&field_spec)?; write!(writer, " cwd: ")?; writer.reset()?; writeln!(writer, "{}", cwd)?; } for (name, info) in &info.tests { writer.set_color(&test_name_spec)?; write!(writer, " {}", name)?; writer.reset()?; if !info.filter_match.is_match() { write!(writer, " (skipped)")?; } writeln!(writer)?; } writer.reset()?; } Ok(()) } fn field_spec() -> ColorSpec { let mut color_spec = ColorSpec::new(); color_spec .set_fg(Some(termcolor::Color::Yellow)) .set_bold(true); color_spec } } impl TestBinary { /// Run this binary with and without --ignored and get the corresponding outputs. fn exec(&self) -> Result<(String, String)> { let non_ignored = self.exec_single(false)?; let ignored = self.exec_single(true)?; Ok((non_ignored, ignored)) } fn exec_single(&self, ignored: bool) -> Result<String> { let mut argv = vec!["--list", "--format", "terse"]; if ignored { argv.push("--ignored"); } let mut cmd = cmd(AsRef::<Path>::as_ref(&self.binary), argv).stdout_capture(); if let Some(cwd) = &self.cwd { cmd = cmd.dir(cwd); }; cmd.read().with_context(|| { format!( "running '{} --list --format --terse{}' failed", self.binary, if ignored { " --ignored" } else { "" } ) }) } } /// Represents a single test with its associated binary. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct TestInstance<'a> { /// The name of the test. pub name: &'a str, /// The test binary. pub binary: &'a Utf8Path, /// A unique identifier for this binary, typically the package + binary name defined in /// `Cargo.toml`. pub binary_id: &'a str, /// Information about the test. pub info: &'a RustTestInfo, /// The working directory for this test. If None, the test will not be changed. pub cwd: Option<&'a Utf8Path>, } impl<'a> TestInstance<'a> { /// Creates a new `TestInstance`. pub(crate) fn new( name: &'a (impl AsRef<str> + ?Sized), binary: &'a (impl AsRef<Utf8Path> + ?Sized), binary_id: &'a str, info: &'a RustTestInfo, cwd: Option<&'a Utf8Path>, ) -> Self { Self { name: name.as_ref(), binary: binary.as_ref(), binary_id, info, cwd, } } } pub(super) fn test_bin_spec() -> ColorSpec { let mut color_spec = ColorSpec::new(); color_spec .set_fg(Some(termcolor::Color::Magenta)) .set_bold(true); color_spec } pub(super) fn test_name_spec() -> ColorSpec { let mut color_spec = ColorSpec::new(); color_spec .set_fg(Some(termcolor::Color::Blue)) .set_bold(true); color_spec } #[cfg(test)] mod tests { use super::*; use crate::{ output::SerializableFormat, test_filter::{FilterMatch, MismatchReason, RunIgnored}, }; use indoc::indoc; use maplit::btreemap; use pretty_assertions::assert_eq; use std::iter; #[test] fn test_parse() { let non_ignored_output = indoc! {" tests::foo::test_bar: test tests::baz::test_quux: test "}; let ignored_output = indoc! {" tests::ignored::test_bar: test tests::baz::test_ignored: test "}; let test_filter = TestFilterBuilder::any(RunIgnored::Default); let fake_cwd: Utf8PathBuf = "/fake/cwd".into(); let fake_binary_id = "fake-package".to_owned(); let test_binary = TestBinary { binary: "/fake/binary".into(), cwd: Some(fake_cwd.clone()), binary_id: fake_binary_id.clone(), }; let test_list = TestList::new_with_outputs( iter::once((test_binary, &non_ignored_output, &ignored_output)), &test_filter, ) .expect("valid output"); assert_eq!( test_list.test_binaries, btreemap! { "/fake/binary".into() => TestBinInfo { tests: btreemap! { "tests::foo::test_bar".to_owned() => RustTestInfo { ignored: false, filter_match: FilterMatch::Matches, }, "tests::baz::test_quux".to_owned() => RustTestInfo { ignored: false, filter_match: FilterMatch::Matches, }, "tests::ignored::test_bar".to_owned() => RustTestInfo { ignored: true, filter_match: FilterMatch::Mismatch { reason: MismatchReason::Ignored }, }, "tests::baz::test_ignored".to_owned() => RustTestInfo { ignored: true, filter_match: FilterMatch::Mismatch { reason: MismatchReason::Ignored }, }, }, cwd: Some(fake_cwd), binary_id: fake_binary_id, } } ); // Check that the expected outputs are valid. static EXPECTED_PLAIN: &str = indoc! {" /fake/binary: cwd: /fake/cwd tests::baz::test_ignored (skipped) tests::baz::test_quux tests::foo::test_bar tests::ignored::test_bar (skipped) "}; static EXPECTED_JSON_PRETTY: &str = indoc! {r#" { "test-count": 4, "test-binaries": { "/fake/binary": { "binary-id": "fake-package", "tests": { "tests::baz::test_ignored": { "ignored": true, "filter-match": { "status": "mismatch", "reason": "ignored" } }, "tests::baz::test_quux": { "ignored": false, "filter-match": { "status": "matches" } }, "tests::foo::test_bar": { "ignored": false, "filter-match": { "status": "matches" } }, "tests::ignored::test_bar": { "ignored": true, "filter-match": { "status": "mismatch", "reason": "ignored" } } }, "cwd": "/fake/cwd" } } }"#}; assert_eq!( test_list .to_string(OutputFormat::Plain) .expect("plain succeeded"), EXPECTED_PLAIN ); assert_eq!( test_list .to_string(OutputFormat::Serializable(SerializableFormat::JsonPretty)) .expect("json-pretty succeeded"), EXPECTED_JSON_PRETTY ); } }
// Cloning when Handling an Option or a Result pub struct large_string_vec { // we may have a "String" in a specific position collection: Vec<(char, Option<String>)>, } // error impl impl large_string_vec { pub fn error_unwrap(&mut self) -> Result<(), char> { for iterm in &self.collection { if iterm.1.is_some() { // cannot move out of borrowed content // use clone ? : iterm.1.cloned().unwrap().contains(iterm.0) // not so good for large number of String in the vec if iterm.1.unwrap().contains(iterm.0) { return Err(iterm.0); } } } Ok(()) } } // to improve the above, first think the two functions below // pub fn unwrap(self) -> T; // pub fn as_ref(&self) -> Option<&T>; impl large_string_vec { pub fn test_as_ref(&mut self) -> Result<(), char> { for iterm in &self.collection { if iterm.1.is_some() { if iterm.1.as_ref().unwrap().contains(iterm.0) { return Err(iterm.0); } } } Ok(()) } // another effective way impl large_string_vec { pub fn test_if_let(&mut self) -> Result<(), char> { for iterm in &self.collection { if let Some(text) = iterm.1 { if text.contains(iterm.0) { return Err(iterm.0); } } } Ok(()) }
#[macro_use] mod common; use common::util::*; static UTIL_NAME: &'static str = "ln"; #[test] fn test_symlink_existing_file() { let (at, mut ucmd) = testing(UTIL_NAME); let file = "test_symlink_existing_file"; let link = "test_symlink_existing_file_link"; at.touch(file); let result = ucmd.args(&["-s", file, link]).run(); assert_empty_stderr!(result); assert!(result.success); assert!(at.file_exists(file)); assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file); } #[test] fn test_symlink_dangling_file() { let (at, mut ucmd) = testing(UTIL_NAME); let file = "test_symlink_dangling_file"; let link = "test_symlink_dangling_file_link"; let result = ucmd.args(&["-s", file, link]).run(); assert_empty_stderr!(result); assert!(result.success); assert!(!at.file_exists(file)); assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file); } #[test] fn test_symlink_existing_directory() { let (at, mut ucmd) = testing(UTIL_NAME); let dir = "test_symlink_existing_dir"; let link = "test_symlink_existing_dir_link"; at.mkdir(dir); let result = ucmd.args(&["-s", dir, link]).run(); assert_empty_stderr!(result); assert!(result.success); assert!(at.dir_exists(dir)); assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), dir); } #[test] fn test_symlink_dangling_directory() { let (at, mut ucmd) = testing(UTIL_NAME); let dir = "test_symlink_dangling_dir"; let link = "test_symlink_dangling_dir_link"; let result = ucmd.args(&["-s", dir, link]).run(); assert_empty_stderr!(result); assert!(result.success); assert!(!at.dir_exists(dir)); assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), dir); } #[test] fn test_symlink_circular() { let (at, mut ucmd) = testing(UTIL_NAME); let link = "test_symlink_circular"; let result = ucmd.args(&["-s", link]).run(); assert_empty_stderr!(result); assert!(result.success); assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), link); } #[test] fn test_symlink_dont_overwrite() { let (at, mut ucmd) = testing(UTIL_NAME); let file = "test_symlink_dont_overwrite"; let link = "test_symlink_dont_overwrite_link"; at.touch(file); at.touch(link); let result = ucmd.args(&["-s", file, link]).run(); assert!(!result.success); assert!(at.file_exists(file)); assert!(at.file_exists(link)); assert!(!at.is_symlink(link)); } #[test] fn test_symlink_overwrite_force() { let (at, mut ucmd) = testing(UTIL_NAME); let file_a = "test_symlink_overwrite_force_a"; let file_b = "test_symlink_overwrite_force_b"; let link = "test_symlink_overwrite_force_link"; // Create symlink at.symlink(file_a, link); assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file_a); // Force overwrite of existing symlink let result = ucmd.args(&["--force", "-s", file_b, link]).run(); assert!(result.success); assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file_b); } #[test] fn test_symlink_interactive() { let ts = TestSet::new(UTIL_NAME); let at = &ts.fixtures; let file = "test_symlink_interactive_file"; let link = "test_symlink_interactive_file_link"; at.touch(file); at.touch(link); let result1 = ts.util_cmd() .args(&["-i", "-s", file, link]) .run_piped_stdin("n"); assert_empty_stderr!(result1); assert!(result1.success); assert!(at.file_exists(file)); assert!(!at.is_symlink(link)); let result2 = ts.util_cmd() .args(&["-i", "-s", file, link]) .run_piped_stdin("Yesh"); assert_empty_stderr!(result2); assert!(result2.success); assert!(at.file_exists(file)); assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file); } #[test] fn test_symlink_simple_backup() { let (at, mut ucmd) = testing(UTIL_NAME); let file = "test_symlink_simple_backup"; let link = "test_symlink_simple_backup_link"; at.touch(file); at.symlink(file, link); assert!(at.file_exists(file)); assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file); let result = ucmd.args(&["-b", "-s", file, link]).run(); assert_empty_stderr!(result); assert!(result.success); assert!(at.file_exists(file)); assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file); let backup = &format!("{}~", link); assert!(at.is_symlink(backup)); assert_eq!(at.resolve_link(backup), file); } #[test] fn test_symlink_custom_backup_suffix() { let (at, mut ucmd) = testing(UTIL_NAME); let file = "test_symlink_custom_backup_suffix"; let link = "test_symlink_custom_backup_suffix_link"; let suffix = "super-suffix-of-the-century"; at.touch(file); at.symlink(file, link); assert!(at.file_exists(file)); assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file); let arg = &format!("--suffix={}", suffix); let result = ucmd.args(&["-b", arg, "-s", file, link]).run(); assert_empty_stderr!(result); assert!(result.success); assert!(at.file_exists(file)); assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file); let backup = &format!("{}{}", link, suffix); assert!(at.is_symlink(backup)); assert_eq!(at.resolve_link(backup), file); } #[test] fn test_symlink_backup_numbering() { let (at, mut ucmd) = testing(UTIL_NAME); let file = "test_symlink_backup_numbering"; let link = "test_symlink_backup_numbering_link"; at.touch(file); at.symlink(file, link); assert!(at.file_exists(file)); assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file); let result = ucmd.args(&["-s", "--backup=t", file, link]).run(); assert_empty_stderr!(result); assert!(result.success); assert!(at.file_exists(file)); assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file); let backup = &format!("{}.~1~", link); assert!(at.is_symlink(backup)); assert_eq!(at.resolve_link(backup), file); } #[test] fn test_symlink_existing_backup() { let (at, mut ucmd) = testing(UTIL_NAME); let file = "test_symlink_existing_backup"; let link = "test_symlink_existing_backup_link"; let link_backup = "test_symlink_existing_backup_link.~1~"; let resulting_backup = "test_symlink_existing_backup_link.~2~"; // Create symlink and verify at.touch(file); at.symlink(file, link); assert!(at.file_exists(file)); assert!(at.is_symlink(link)); assert_eq!(at.resolve_link(link), file); // Create backup symlink and verify at.symlink(file, link_backup); assert!(at.file_exists(file)); assert!(at.is_symlink(link_backup)); assert_eq!(at.resolve_link(link_backup), file); let result = ucmd.args(&["-s", "--backup=nil", file, link]).run(); assert_empty_stderr!(result); assert!(result.success); assert!(at.file_exists(file)); assert!(at.is_symlink(link_backup)); assert_eq!(at.resolve_link(link_backup), file); assert!(at.is_symlink(resulting_backup)); assert_eq!(at.resolve_link(resulting_backup), file); } #[test] fn test_symlink_target_dir() { let (at, mut ucmd) = testing(UTIL_NAME); let dir = "test_ln_target_dir_dir"; let file_a = "test_ln_target_dir_file_a"; let file_b = "test_ln_target_dir_file_b"; at.touch(file_a); at.touch(file_b); at.mkdir(dir); let result = ucmd.args(&["-s", "-t", dir, file_a, file_b]).run(); assert_empty_stderr!(result); assert!(result.success); let file_a_link = &format!("{}/{}", dir, file_a); assert!(at.is_symlink(file_a_link)); assert_eq!(at.resolve_link(file_a_link), file_a); let file_b_link = &format!("{}/{}", dir, file_b); assert!(at.is_symlink(file_b_link)); assert_eq!(at.resolve_link(file_b_link), file_b); } #[test] fn test_symlink_overwrite_dir() { let (at, mut ucmd) = testing(UTIL_NAME); let path_a = "test_symlink_overwrite_dir_a"; let path_b = "test_symlink_overwrite_dir_b"; at.touch(path_a); at.mkdir(path_b); let result = ucmd.args(&["-s", "-T", path_a, path_b]).run(); assert_empty_stderr!(result); assert!(result.success); assert!(at.file_exists(path_a)); assert!(at.is_symlink(path_b)); assert_eq!(at.resolve_link(path_b), path_a); } #[test] fn test_symlink_overwrite_nonempty_dir() { let (at, mut ucmd) = testing(UTIL_NAME); let path_a = "test_symlink_overwrite_nonempty_dir_a"; let path_b = "test_symlink_overwrite_nonempty_dir_b"; let dummy = "test_symlink_overwrite_nonempty_dir_b/file"; at.touch(path_a); at.mkdir(path_b); at.touch(dummy); let result = ucmd.args(&["-v", "-T", "-s", path_a, path_b]).run(); // Not same error as GNU; the error message is a Rust builtin // TODO: test (and implement) correct error message (or at least decide whether to do so) // Current: "ln: error: Directory not empty (os error 66)" // GNU: "ln: cannot link 'a' to 'b': Directory not empty" assert!(result.stderr.len() > 0); // Verbose output for the link should not be shown on failure assert!(result.stdout.len() == 0); assert!(!result.success); assert!(at.file_exists(path_a)); assert!(at.dir_exists(path_b)); } #[test] fn test_symlink_errors() { let (at, mut ucmd) = testing(UTIL_NAME); let dir = "test_symlink_errors_dir"; let file_a = "test_symlink_errors_file_a"; let file_b = "test_symlink_errors_file_b"; at.mkdir(dir); at.touch(file_a); at.touch(file_b); // $ ln -T -t a b // ln: cannot combine --target-directory (-t) and --no-target-directory (-T) let result = ucmd.args(&["-T", "-t", dir, file_a, file_b]).run(); assert_eq!(result.stderr, "ln: error: cannot combine --target-directory (-t) and --no-target-directory \ (-T)\n"); assert!(!result.success); } #[test] fn test_symlink_verbose() { let ts = TestSet::new(UTIL_NAME); let at = &ts.fixtures; let file_a = "test_symlink_verbose_file_a"; let file_b = "test_symlink_verbose_file_b"; at.touch(file_a); let result = ts.util_cmd().args(&["-v", file_a, file_b]).run(); assert_empty_stderr!(result); assert_eq!(result.stdout, format!("'{}' -> '{}'\n", file_b, file_a)); assert!(result.success); at.touch(file_b); let result = ts.util_cmd().args(&["-v", "-b", file_a, file_b]).run(); assert_empty_stderr!(result); assert_eq!(result.stdout, format!("'{}' -> '{}' (backup: '{}~')\n", file_b, file_a, file_b)); assert!(result.success); }
// This file is part of ICU4X. For terms of use, please see the file // called LICENSE at the top level of the ICU4X source tree // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). pub mod structs; use icu_datetime::options::{length, DateTimeFormatOptions}; use std::fs::File; use std::io::BufReader; #[allow(dead_code)] pub fn get_fixture(name: &str) -> std::io::Result<structs::Fixture> { let file = File::open(format!("./benches/fixtures/tests/{}.json", name))?; let reader = BufReader::new(file); Ok(serde_json::from_reader(reader)?) } #[allow(dead_code)] pub fn get_patterns_fixture() -> std::io::Result<structs::PatternsFixture> { let file = File::open("./benches/fixtures/tests/patterns.json")?; let reader = BufReader::new(file); Ok(serde_json::from_reader(reader)?) } #[allow(dead_code)] pub fn get_options(input: &structs::TestOptions) -> DateTimeFormatOptions { let length = length::Bag { date: input.length.date.as_ref().map(|date| match date { structs::TestLength::Full => length::Date::Full, structs::TestLength::Long => length::Date::Long, structs::TestLength::Medium => length::Date::Medium, structs::TestLength::Short => length::Date::Short, }), time: input.length.time.as_ref().map(|time| match time { structs::TestLength::Full => length::Time::Full, structs::TestLength::Long => length::Time::Long, structs::TestLength::Medium => length::Time::Medium, structs::TestLength::Short => length::Time::Short, }), ..Default::default() }; length.into() }
macro_rules! say_hello { // `()` menandakan bahwa macro tidak punya arg () => { println!("Hello world!"); }; } fn main() { println!("Hello world!"); say_hello!(); }
use std::cmp::Ordering; use std::vec::Vec; // Implements sequential search with a search key as a sentinel // Input: An array a of n elements and a search key k // Output: The index of the first element in a[0..n-1] whose value is equal to k // or -1 if no such element is found fn sequential_search_2(a: &[u8], k: u8) -> i8 { let n = a.len(); let mut v: Vec<u8> = a.to_vec(); v.push(k); let mut i = 0; while v[i] != k { i = i + 1; } let ret: i8 = match i.cmp(&n) { Ordering::Equal => -1, Ordering::Less => i as i8, Ordering::Greater => -1, }; ret } fn main() { let a: [u8; 7] = [89, 45, 68, 90, 29, 34, 17]; println!("Array to search: {:?}", a); println!("Index of '90': {}", sequential_search_2(&a, 90)); println!("Index of '20': {}", sequential_search_2(&a, 20)); }
use chrono::{prelude::*, Duration}; use juniper::{execute_sync, EmptyMutation, EmptySubscription, Variables}; #[derive(juniper::GraphQLScalarValue)] struct SampleDate(DateTime<Utc>); struct Query; #[juniper::graphql_object(context = Context)] impl Query { fn now() -> SampleDate { SampleDate(Utc::now()) } fn nextDay(d: SampleDate) -> SampleDate { SampleDate(d.0 + Duration::days(1)) } } #[derive(Clone, Copy, Debug)] struct Context; impl juniper::Context for Context {} type Schema = juniper::RootNode<'static, Query, EmptyMutation<Context>, EmptySubscription<Context>>; fn main() { let ctx = Context; let schema = Schema::new( Query, EmptyMutation::new(), EmptySubscription::new(), ); let q1 = r#" { now } "#; let (r1, _) = execute_sync(q1, None, &schema, &Variables::new(), &ctx).unwrap(); println!("{:?}", r1); let s1 = serde_json::to_string_pretty(&r1).unwrap(); println!("{}", s1); let q2 = r#" { nextDay(d: "2022-10-31T05:00:00Z") } "#; let (r2, _) = execute_sync(q2, None, &schema, &Variables::new(), &ctx).unwrap(); println!("{:?}", r2); let s2 = serde_json::to_string_pretty(&r2).unwrap(); println!("{}", s2); }
use crate::lint::core::Filter; pub mod filter_nothing; pub mod filter_test; pub fn get_all_filters() -> Vec<Box<dyn Filter>> { vec![Box::new(filter_test::TestModuleFilter)] }
// revisions: base nll // ignore-compare-mode-nll //[nll] compile-flags: -Z borrowck=mir use std::any::Any; fn foo<T: Any>(value: &T) -> Box<dyn Any> { Box::new(value) as Box<dyn Any> //[base]~^ ERROR E0759 //[nll]~^^ ERROR lifetime may not live long enough } fn main() { let _ = foo(&5); }
extern crate itertools; use std::fs::File; use std::io::BufReader; use std::io::BufRead; use std::collections::HashSet; use itertools::Itertools; #[derive(PartialEq, Eq, Hash, Clone)] struct Coord { x: i32, y: i32, } fn step(lights: &HashSet<Coord>) -> HashSet<Coord> { let mut new_state: HashSet<Coord> = HashSet::new(); for (x, y) in (0..100).cartesian_product(0..100) { let mut neighbours = 0; for (c, d) in (-1..2).cartesian_product(-1..2) { if c == 0 && d == 0 { continue; } if lights.contains(&Coord{x: x+c, y: y+d}) { neighbours += 1; } } let c = Coord{x:x, y:y}; if lights.contains(&c) && (neighbours == 2 || neighbours == 3) { new_state.insert(c); } else if !lights.contains(&c) && neighbours == 3 { new_state.insert(c); } } new_state } fn main() { let f = File::open("day18.in") .ok() .expect("Failed to open input"); let file = BufReader::new(&f); let mut input: HashSet<Coord> = HashSet::new(); for (y, line) in file.lines().enumerate() { let line = line.unwrap(); for (x, cell) in line.chars().enumerate() { if cell == '#' { input.insert(Coord{ x: x as i32, y: y as i32}); } } } let mut state = input.clone(); for _ in 0..100 { state = step(&state); } println!("{}", state.len()); let corners: HashSet<_> = [ Coord{x: 0, y: 0}, Coord{x: 0, y: 99}, Coord{x: 99, y: 0}, Coord{x: 99, y: 99} ].iter().cloned().collect(); state = input.clone().union(&corners).cloned().collect(); for _ in 0..100 { state = step(&state).union(&corners).cloned().collect(); } println!("{}", state.len()); }
use std::env; fn main() { let zmq_has = match env::var("ZMQ_HAS") { Ok(value) => value, Err(..) => panic!("Please set the ZMQ_HAS environment variable (e.g. \"ipc,pgm,tipc,norm,curve,gssapi\")") }; println!("rerun-if-env-changed=ZMQ_HAS"); for has in zmq_has.split(",") { println!("cargo:rustc-cfg=ZMQ_HAS_{}=\"1\"", has.to_uppercase()); } }
use std::cmp::{max, min}; use std::collections::{HashMap, HashSet}; use itertools::Itertools; use whiteread::parse_line; fn main() { let (n, m): (usize, usize) = parse_line().unwrap(); let mut paths: Vec<Vec<usize>> = vec![vec![]; n + 1]; for _ in 0..m { let (a, b): (usize, usize) = parse_line().unwrap(); paths[a].push(b); } let mut ans = 0; for i in 1..=n { let mut h = HashSet::new(); ans += dfs(0, i, &paths, &mut h); } println!("{}", ans); } fn dfs( mut current: usize, target: usize, paths: &Vec<Vec<usize>>, checked: &mut HashSet<usize>, ) -> usize { if checked.contains(&target) { return current; } checked.insert(target); current += 1; for p in paths[target].iter() { current = dfs(current, *p, paths, checked); } return current; }
#[cfg(test)] mod contract;
use crate::protocol::parts::{ExecutionResult, ServerError}; // use std::backtrace::Backtrace; use thiserror::Error; /// A list specifying categories of [`HdbError`](crate::HdbError). /// #[derive(Error, Debug)] //Copy, Clone, Eq, PartialEq, #[non_exhaustive] pub enum HdbError { /// Deserialization of a `ResultSet`, a `Row`, a single `HdbValue`, /// or an `OutputParameter` failed (methods `try_into()`). #[error("Error occured in deserialization")] Deserialization { /// The causing Error. #[from] source: serde_db::de::DeserializationError, // backtrace: Backtrace, }, /// Serialization of a `ParameterDescriptor` or a `ParameterRow` failed. #[error("Error occured in serialization")] Serialization { /// The causing Error. #[from] source: serde_db::ser::SerializationError, // backtrace: Backtrace, }, /// Some error occured while decoding CESU-8. This indicates a server issue! #[error("Some error occured while decoding CESU-8")] Cesu8 { /// The causing Error. #[from] source: cesu8::Cesu8DecodingError, // backtrace: Backtrace, }, /// Erroneous Connection Parameters, e.g. from a malformed connection URL. #[error("Erroneous Connection Parameters")] ConnParams { /// The causing Error. source: Box<dyn std::error::Error + Send + Sync + 'static>, // backtrace: Backtrace, }, /// Database server responded with an error; /// the contained `ServerError` describes the conrete reason. #[error("Database server responded with an error")] DbError { /// The causing Error. #[from] source: ServerError, // backtrace: Backtrace, }, /// TLS set up failed because the server name was not valid. #[error("TLS set up failed, because the server name was not valid")] TlsServerName { /// The causing Error. #[from] source: rustls::client::InvalidDnsNameError, }, /// TLS protocol error. #[error( "TLS set up failed, after setting up the TCP connection; is the database prepared for TLS?" )] TlsProtocol { /// The causing Error. #[from] source: rustls::Error, }, /// Error occured while evaluating an `HdbResponse` or an `HdbReturnValue`. #[error("Error occured while evaluating a HdbResponse or an HdbReturnValue")] Evaluation(&'static str), /// Database server responded with at least one error. #[error("Database server responded with at least one error")] ExecutionResults(Vec<ExecutionResult>), /// Implementation error. #[error("Implementation error: {}", _0)] Impl(&'static str), /// Implementation error. #[error("Implementation error: {}", _0)] ImplDetailed(String), /// Error occured in thread synchronization. #[cfg(feature = "sync")] #[error("Error occured in thread synchronization")] Poison, /// An error occurred on the server that requires the session to be terminated. #[error("An error occurred on the server that requires the session to be terminated")] SessionClosingTransactionError, /// Error occured in communication with the database. // #[error( // "Error occured in communication with the database; \ // if this happens during setup, then a frequent cause is that TLS \ // was attempted but is not supported by the database instance" // )] #[error(transparent)] Io { /// The causing Error. #[from] source: std::io::Error, // backtrace: Backtrace, }, /// Error caused by wrong usage. #[error("Wrong usage: {}", _0)] Usage(&'static str), /// Error caused by wrong usage. #[error("Wrong usage: {}", _0)] UsageDetailed(String), } /// Abbreviation of `Result<T, HdbError>`. pub type HdbResult<T> = std::result::Result<T, HdbError>; impl HdbError { /// Returns the contained `ServerError`, if any. /// /// This method helps in case you need programmatic access to e.g. the error code. /// /// Example: /// /// ```rust,no_run /// # use hdbconnect::{Connection, HdbError, HdbResult}; /// # use hdbconnect::IntoConnectParams; /// # fn main() -> HdbResult<()> { /// # let hdb_result: HdbResult<()> = Err(HdbError::Usage("test")); /// # let mut connection = Connection::new("".into_connect_params()?)?; /// if let Err(hdberror) = hdb_result { /// if let Some(server_error) = hdberror.server_error() { /// let sys_m_error_code: (i32, String, String) = connection /// .query(&format!( /// "select * from SYS.M_ERROR_CODES where code = {}", /// server_error.code() /// ))?.try_into()?; /// println!("sys_m_error_code: {:?}", sys_m_error_code); /// } /// } /// # Ok(()) /// # } /// ``` pub fn server_error(&self) -> Option<&ServerError> { match self { Self::DbError { source: server_error, } => Some(server_error), _ => None, } } /// Reveal the inner error pub fn inner(&self) -> Option<&dyn std::error::Error> { match self { Self::Deserialization { source: e } => Some(e), Self::Serialization { source: e } => Some(e), Self::Cesu8 { source: e } => Some(e), Self::ConnParams { source: e } => Some(&**e), Self::DbError { source: e } => Some(e), Self::TlsServerName { source: e } => Some(e), Self::TlsProtocol { source: e } => Some(e), Self::Io { source: e } => Some(e), _ => None, } } pub(crate) fn conn_params(error: Box<dyn std::error::Error + Send + Sync + 'static>) -> Self { Self::ConnParams { source: error } } } #[cfg(feature = "sync")] impl<G> From<std::sync::PoisonError<G>> for HdbError { fn from(_error: std::sync::PoisonError<G>) -> Self { Self::Poison } }
/// Generates permutation of numbers passed. /// [1, 2, 3] -> [123, 132, 213, 231, 312, 321] pub fn nums_10(nums: Vec<u32>) -> Vec<u32> { let numlen = nums.len(); if numlen == 1 { nums } else { let mut sols = vec![]; for (index, number) in nums.iter().enumerate() { let mut new_vec = nums.clone(); new_vec.remove(index); for n in nums_10(new_vec).clone().iter() { let pow: u32 = (numlen - 1) as u32; sols.push(number * 10u32.pow(pow) + n); } } sols } } /// Generates permutation of numbers passed. /// [1, 2, 3] -> [123, 132, 213, 231, 312, 321] pub fn perms_r(nums: Vec<u32>, r: usize) -> Vec<u32> { let numlen = nums.len(); if r > numlen { return nums; } if r == 1 { return nums; } if numlen == 1 { nums } else { let mut sols = vec![]; for (index, number) in nums.iter().enumerate() { let mut new_vec = nums.clone(); new_vec.remove(index); for n in perms_r(new_vec, r - 1).clone().iter() { let pow: u32 = (r - 1) as u32; sols.push(number * 10u32.pow(pow) + n); } } sols } } pub fn all_perms(nums: Vec<u32>) -> Vec<u32> { let numlen = nums.len(); if numlen == 1 { nums } else { let mut sols = vec![]; for (index, number) in nums.iter().enumerate() { let mut new_vec = nums.clone(); new_vec.remove(index); for n in all_perms(new_vec).clone().iter() { let pow: u32 = (numlen - 1) as u32; sols.push(number * 10u32.pow(pow) + n); if !sols.contains(n) { sols.push(*n); } } sols.push(*number); } sols } } // pub fn str_perm(chars: Vec<String>) -> Vec<String> { let len = chars.len(); if len == 1 { chars } else { let mut sols = vec![]; for (index, c) in chars.iter().enumerate() { let mut new_vec = chars.clone(); if c == " " && (len == 10) { break; } new_vec.remove(index); for n in str_perm(new_vec).clone().iter() { sols.push(format!("{}{}", c, n)); } } sols } }
use codec::Encode; use pallet_mixnet::types::{ Ballot, DecryptedShare, DecryptedShareProof, NrOfShuffles, PublicKey as SubstratePK, PublicKeyShare, PublicParameters, Title, Topic, TopicId, TopicResult, VoteId, VotePhase, }; use substrate_subxt::{Call, EventsDecoder, NodeTemplateRuntime}; #[derive(Encode)] pub struct CreateVote { pub vote_id: VoteId, pub title: Title, pub params: PublicParameters, pub topics: Vec<Topic>, pub batch_size: u64, } impl Call<NodeTemplateRuntime> for CreateVote { const MODULE: &'static str = "PalletMixnet"; const FUNCTION: &'static str = "create_vote"; fn events_decoder(_decoder: &mut EventsDecoder<NodeTemplateRuntime>) { _decoder.register_type_size::<VoteId>("VoteId"); _decoder.register_type_size::<Title>("Title"); _decoder.register_type_size::<PublicParameters>("PublicParameters"); _decoder.register_type_size::<Vec<Topic>>("Vec<Topic>"); _decoder.register_type_size::<u64>("batch_size"); } } #[derive(Encode)] pub struct StoreQuestion { pub vote_id: VoteId, pub topic: Topic, pub batch_size: u64, } impl Call<NodeTemplateRuntime> for StoreQuestion { const MODULE: &'static str = "PalletMixnet"; const FUNCTION: &'static str = "store_question"; fn events_decoder(_decoder: &mut EventsDecoder<NodeTemplateRuntime>) { _decoder.register_type_size::<VoteId>("VoteId"); _decoder.register_type_size::<Topic>("Topic"); _decoder.register_type_size::<u64>("batch_size"); } } #[derive(Encode)] pub struct StorePublicKey { pub vote_id: VoteId, pub pk: SubstratePK, } impl Call<NodeTemplateRuntime> for StorePublicKey { const MODULE: &'static str = "PalletMixnet"; const FUNCTION: &'static str = "store_public_key"; fn events_decoder(_decoder: &mut EventsDecoder<NodeTemplateRuntime>) { _decoder.register_type_size::<VoteId>("VoteId"); _decoder.register_type_size::<SubstratePK>("SubstratePK"); } } #[derive(Encode)] pub struct StorePublicKeyShare { pub vote_id: VoteId, pub pk_share: PublicKeyShare, } impl Call<NodeTemplateRuntime> for StorePublicKeyShare { const MODULE: &'static str = "PalletMixnet"; const FUNCTION: &'static str = "store_public_key_share"; fn events_decoder(_decoder: &mut EventsDecoder<NodeTemplateRuntime>) { _decoder.register_type_size::<VoteId>("VoteId"); _decoder.register_type_size::<PublicKeyShare>("PublicKeyShare"); } } #[derive(Encode)] pub struct CombinePublicKeyShares { pub vote_id: VoteId, } impl Call<NodeTemplateRuntime> for CombinePublicKeyShares { const MODULE: &'static str = "PalletMixnet"; const FUNCTION: &'static str = "combine_public_key_shares"; fn events_decoder(_decoder: &mut EventsDecoder<NodeTemplateRuntime>) { _decoder.register_type_size::<VoteId>("VoteId"); _decoder.register_type_size::<SubstratePK>("SubstratePK"); } } #[derive(Encode)] pub struct SetVotePhase { pub vote_id: VoteId, pub vote_phase: VotePhase, } impl Call<NodeTemplateRuntime> for SetVotePhase { const MODULE: &'static str = "PalletMixnet"; const FUNCTION: &'static str = "set_vote_phase"; fn events_decoder(_decoder: &mut EventsDecoder<NodeTemplateRuntime>) { _decoder.register_type_size::<VoteId>("VoteId"); _decoder.register_type_size::<VotePhase>("VotePhase"); } } #[derive(Encode)] pub struct CastBallot { pub vote_id: VoteId, pub ballot: Ballot, } impl Call<NodeTemplateRuntime> for CastBallot { const MODULE: &'static str = "PalletMixnet"; const FUNCTION: &'static str = "cast_ballot"; fn events_decoder(_decoder: &mut EventsDecoder<NodeTemplateRuntime>) { _decoder.register_type_size::<VoteId>("VoteId"); _decoder.register_type_size::<Ballot>("Ballot"); } } #[derive(Encode)] pub struct SubmitPartialDecryption { pub vote_id: VoteId, pub topic_id: TopicId, pub shares: Vec<DecryptedShare>, pub proof: DecryptedShareProof, pub nr_of_shuffles: NrOfShuffles, } impl Call<NodeTemplateRuntime> for SubmitPartialDecryption { const MODULE: &'static str = "PalletMixnet"; const FUNCTION: &'static str = "submit_decrypted_shares"; fn events_decoder(_decoder: &mut EventsDecoder<NodeTemplateRuntime>) { _decoder.register_type_size::<VoteId>("VoteId"); _decoder.register_type_size::<TopicId>("TopicId"); _decoder.register_type_size::<Vec<DecryptedShare>>("Vec<DecryptedShare>"); _decoder.register_type_size::<DecryptedShareProof>("DecryptedShareProof"); _decoder.register_type_size::<NrOfShuffles>("NrOfShuffles"); } } #[derive(Encode)] pub struct CombineDecryptedShares { pub vote_id: VoteId, pub topic_id: TopicId, pub encoded: bool, pub nr_of_shuffles: NrOfShuffles, } impl Call<NodeTemplateRuntime> for CombineDecryptedShares { const MODULE: &'static str = "PalletMixnet"; const FUNCTION: &'static str = "combine_decrypted_shares"; fn events_decoder(_decoder: &mut EventsDecoder<NodeTemplateRuntime>) { _decoder.register_type_size::<VoteId>("VoteId"); _decoder.register_type_size::<TopicId>("TopicId"); _decoder.register_type_size::<bool>("bool"); _decoder.register_type_size::<NrOfShuffles>("NrOfShuffles"); _decoder.register_type_size::<TopicResult>("TopicResult"); } }
// // This file contains common utilities for dealing with PostgreSQL WAL files and // LSNs. // // Many of these functions have been copied from PostgreSQL, and rewritten in // Rust. That's why they don't follow the usual Rust naming conventions, they // have been named the same as the corresponding PostgreSQL functions instead. // use crate::pg_constants; use crate::CheckPoint; use crate::ControlFileData; use crate::FullTransactionId; use crate::XLogLongPageHeaderData; use crate::XLogPageHeaderData; use crate::XLogRecord; use crate::XLOG_PAGE_MAGIC; use anyhow::{bail, Result}; use byteorder::{ByteOrder, LittleEndian}; use bytes::{Buf, Bytes}; use bytes::{BufMut, BytesMut}; use crc32c::*; use log::*; use std::cmp::max; use std::cmp::min; use std::fs::{self, File}; use std::io::prelude::*; use std::io::SeekFrom; use std::path::{Path, PathBuf}; use std::time::SystemTime; use zenith_utils::lsn::Lsn; pub const XLOG_FNAME_LEN: usize = 24; pub const XLOG_BLCKSZ: usize = 8192; pub const XLP_FIRST_IS_CONTRECORD: u16 = 0x0001; pub const XLP_REM_LEN_OFFS: usize = 2 + 2 + 4 + 8; pub const XLOG_RECORD_CRC_OFFS: usize = 4 + 4 + 8 + 1 + 1 + 2; pub const MAX_SEND_SIZE: usize = XLOG_BLCKSZ * 16; pub const XLOG_SIZE_OF_XLOG_SHORT_PHD: usize = std::mem::size_of::<XLogPageHeaderData>(); pub const XLOG_SIZE_OF_XLOG_LONG_PHD: usize = std::mem::size_of::<XLogLongPageHeaderData>(); pub const XLOG_SIZE_OF_XLOG_RECORD: usize = std::mem::size_of::<XLogRecord>(); #[allow(clippy::identity_op)] pub const SIZE_OF_XLOG_RECORD_DATA_HEADER_SHORT: usize = 1 * 2; pub type XLogRecPtr = u64; pub type TimeLineID = u32; pub type TimestampTz = i64; pub type XLogSegNo = u64; const XID_CHECKPOINT_INTERVAL: u32 = 1024; #[allow(non_snake_case)] pub fn XLogSegmentsPerXLogId(wal_segsz_bytes: usize) -> XLogSegNo { (0x100000000u64 / wal_segsz_bytes as u64) as XLogSegNo } #[allow(non_snake_case)] pub fn XLogSegNoOffsetToRecPtr( segno: XLogSegNo, offset: u32, wal_segsz_bytes: usize, ) -> XLogRecPtr { segno * (wal_segsz_bytes as u64) + (offset as u64) } #[allow(non_snake_case)] pub fn XLogFileName(tli: TimeLineID, logSegNo: XLogSegNo, wal_segsz_bytes: usize) -> String { return format!( "{:>08X}{:>08X}{:>08X}", tli, logSegNo / XLogSegmentsPerXLogId(wal_segsz_bytes), logSegNo % XLogSegmentsPerXLogId(wal_segsz_bytes) ); } #[allow(non_snake_case)] pub fn XLogFromFileName(fname: &str, wal_seg_size: usize) -> (XLogSegNo, TimeLineID) { let tli = u32::from_str_radix(&fname[0..8], 16).unwrap(); let log = u32::from_str_radix(&fname[8..16], 16).unwrap() as XLogSegNo; let seg = u32::from_str_radix(&fname[16..24], 16).unwrap() as XLogSegNo; (log * XLogSegmentsPerXLogId(wal_seg_size) + seg, tli) } #[allow(non_snake_case)] pub fn IsXLogFileName(fname: &str) -> bool { return fname.len() == XLOG_FNAME_LEN && fname.chars().all(|c| c.is_ascii_hexdigit()); } #[allow(non_snake_case)] pub fn IsPartialXLogFileName(fname: &str) -> bool { fname.ends_with(".partial") && IsXLogFileName(&fname[0..fname.len() - 8]) } /// If LSN points to the beginning of the page, then shift it to first record, /// otherwise align on 8-bytes boundary (required for WAL records) pub fn normalize_lsn(lsn: Lsn, seg_sz: usize) -> Lsn { if lsn.0 % XLOG_BLCKSZ as u64 == 0 { let hdr_size = if lsn.0 % seg_sz as u64 == 0 { XLOG_SIZE_OF_XLOG_LONG_PHD } else { XLOG_SIZE_OF_XLOG_SHORT_PHD }; lsn + hdr_size as u64 } else { lsn.align() } } pub fn get_current_timestamp() -> TimestampTz { const UNIX_EPOCH_JDATE: u64 = 2440588; /* == date2j(1970, 1, 1) */ const POSTGRES_EPOCH_JDATE: u64 = 2451545; /* == date2j(2000, 1, 1) */ const SECS_PER_DAY: u64 = 86400; const USECS_PER_SEC: u64 = 1000000; match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) { Ok(n) => { ((n.as_secs() - ((POSTGRES_EPOCH_JDATE - UNIX_EPOCH_JDATE) * SECS_PER_DAY)) * USECS_PER_SEC + n.subsec_micros() as u64) as i64 } Err(_) => panic!("SystemTime before UNIX EPOCH!"), } } fn find_end_of_wal_segment( data_dir: &Path, segno: XLogSegNo, tli: TimeLineID, wal_seg_size: usize, start_offset: usize, // start reading at this point ) -> Result<u32> { // step back to the beginning of the page to read it in... let mut offs: usize = start_offset - start_offset % XLOG_BLCKSZ; let mut contlen: usize = 0; let mut wal_crc: u32 = 0; let mut crc: u32 = 0; let mut rec_offs: usize = 0; let mut buf = [0u8; XLOG_BLCKSZ]; let file_name = XLogFileName(tli, segno, wal_seg_size); let mut last_valid_rec_pos: usize = 0; let mut file = File::open(data_dir.join(file_name.clone() + ".partial")).unwrap(); file.seek(SeekFrom::Start(offs as u64))?; let mut rec_hdr = [0u8; XLOG_RECORD_CRC_OFFS]; while offs < wal_seg_size { // we are at the beginning of the page; read it in if offs % XLOG_BLCKSZ == 0 { let bytes_read = file.read(&mut buf)?; if bytes_read != buf.len() { bail!( "failed to read {} bytes from {} at {}", XLOG_BLCKSZ, file_name, offs ); } let xlp_magic = LittleEndian::read_u16(&buf[0..2]); let xlp_info = LittleEndian::read_u16(&buf[2..4]); let xlp_rem_len = LittleEndian::read_u32(&buf[XLP_REM_LEN_OFFS..XLP_REM_LEN_OFFS + 4]); // this is expected in current usage when valid WAL starts after page header if xlp_magic != XLOG_PAGE_MAGIC as u16 { trace!( "invalid WAL file {}.partial magic {} at {:?}", file_name, xlp_magic, Lsn(XLogSegNoOffsetToRecPtr(segno, offs as u32, wal_seg_size)), ); } if offs == 0 { offs = XLOG_SIZE_OF_XLOG_LONG_PHD; if (xlp_info & XLP_FIRST_IS_CONTRECORD) != 0 { offs += ((xlp_rem_len + 7) & !7) as usize; } } else { offs += XLOG_SIZE_OF_XLOG_SHORT_PHD; } // ... and step forward again if asked offs = max(offs, start_offset); // beginning of the next record } else if contlen == 0 { let page_offs = offs % XLOG_BLCKSZ; let xl_tot_len = LittleEndian::read_u32(&buf[page_offs..page_offs + 4]) as usize; if xl_tot_len == 0 { info!( "find_end_of_wal_segment reached zeros at {:?}", Lsn(XLogSegNoOffsetToRecPtr(segno, offs as u32, wal_seg_size)) ); break; // zeros, reached the end } last_valid_rec_pos = offs; offs += 4; rec_offs = 4; contlen = xl_tot_len - 4; rec_hdr[0..4].copy_from_slice(&buf[page_offs..page_offs + 4]); } else { // we're continuing a record, possibly from previous page. let page_offs = offs % XLOG_BLCKSZ; let pageleft = XLOG_BLCKSZ - page_offs; // read the rest of the record, or as much as fits on this page. let n = min(contlen, pageleft); // fill rec_hdr (header up to (but not including) xl_crc field) if rec_offs < XLOG_RECORD_CRC_OFFS { let len = min(XLOG_RECORD_CRC_OFFS - rec_offs, n); rec_hdr[rec_offs..rec_offs + len].copy_from_slice(&buf[page_offs..page_offs + len]); } if rec_offs <= XLOG_RECORD_CRC_OFFS && rec_offs + n >= XLOG_SIZE_OF_XLOG_RECORD { let crc_offs = page_offs - rec_offs + XLOG_RECORD_CRC_OFFS; wal_crc = LittleEndian::read_u32(&buf[crc_offs..crc_offs + 4]); crc = crc32c_append(0, &buf[crc_offs + 4..page_offs + n]); } else { crc ^= 0xFFFFFFFFu32; crc = crc32c_append(crc, &buf[page_offs..page_offs + n]); } crc = !crc; rec_offs += n; offs += n; contlen -= n; if contlen == 0 { crc = !crc; crc = crc32c_append(crc, &rec_hdr); offs = (offs + 7) & !7; // pad on 8 bytes boundary */ if crc == wal_crc { // record is valid, advance the result to its end (with // alignment to the next record taken into account) last_valid_rec_pos = offs; } else { info!( "CRC mismatch {} vs {} at {}", crc, wal_crc, last_valid_rec_pos ); break; } } } } Ok(last_valid_rec_pos as u32) } /// /// Scan a directory that contains PostgreSQL WAL files, for the end of WAL. /// If precise, returns end LSN (next insertion point, basically); /// otherwise, start of the last segment. /// Returns (0, 0) if there is no WAL. /// pub fn find_end_of_wal( data_dir: &Path, wal_seg_size: usize, precise: bool, start_lsn: Lsn, // start reading WAL at this point or later ) -> Result<(XLogRecPtr, TimeLineID)> { let mut high_segno: XLogSegNo = 0; let mut high_tli: TimeLineID = 0; let mut high_ispartial = false; for entry in fs::read_dir(data_dir).unwrap().flatten() { let ispartial: bool; let entry_name = entry.file_name(); let fname = entry_name.to_str().unwrap(); /* * Check if the filename looks like an xlog file, or a .partial file. */ if IsXLogFileName(fname) { ispartial = false; } else if IsPartialXLogFileName(fname) { ispartial = true; } else { continue; } let (segno, tli) = XLogFromFileName(fname, wal_seg_size); if !ispartial && entry.metadata().unwrap().len() != wal_seg_size as u64 { continue; } if segno > high_segno || (segno == high_segno && tli > high_tli) || (segno == high_segno && tli == high_tli && high_ispartial && !ispartial) { high_segno = segno; high_tli = tli; high_ispartial = ispartial; } } if high_segno > 0 { let mut high_offs = 0; /* * Move the starting pointer to the start of the next segment, if the * highest one we saw was completed. */ if !high_ispartial { high_segno += 1; } else if precise { /* otherwise locate last record in last partial segment */ if start_lsn.segment_number(wal_seg_size) > high_segno { bail!( "provided start_lsn {:?} is beyond highest segno {:?} available", start_lsn, high_segno, ); } high_offs = find_end_of_wal_segment( data_dir, high_segno, high_tli, wal_seg_size, start_lsn.segment_offset(wal_seg_size), )?; } let high_ptr = XLogSegNoOffsetToRecPtr(high_segno, high_offs, wal_seg_size); return Ok((high_ptr, high_tli)); } Ok((0, 0)) } pub fn main() { let mut data_dir = PathBuf::new(); data_dir.push("."); let wal_seg_size = 16 * 1024 * 1024; let (wal_end, tli) = find_end_of_wal(&data_dir, wal_seg_size, true, Lsn(0)).unwrap(); println!( "wal_end={:>08X}{:>08X}, tli={}", (wal_end >> 32) as u32, wal_end as u32, tli ); } impl XLogRecord { pub fn from_bytes(buf: &mut Bytes) -> XLogRecord { use zenith_utils::bin_ser::LeSer; XLogRecord::des_from(&mut buf.reader()).unwrap() } pub fn encode(&self) -> Bytes { use zenith_utils::bin_ser::LeSer; self.ser().unwrap().into() } // Is this record an XLOG_SWITCH record? They need some special processing, pub fn is_xlog_switch_record(&self) -> bool { self.xl_info == pg_constants::XLOG_SWITCH && self.xl_rmid == pg_constants::RM_XLOG_ID } } impl XLogPageHeaderData { pub fn from_bytes<B: Buf>(buf: &mut B) -> XLogPageHeaderData { use zenith_utils::bin_ser::LeSer; XLogPageHeaderData::des_from(&mut buf.reader()).unwrap() } } impl XLogLongPageHeaderData { pub fn from_bytes<B: Buf>(buf: &mut B) -> XLogLongPageHeaderData { use zenith_utils::bin_ser::LeSer; XLogLongPageHeaderData::des_from(&mut buf.reader()).unwrap() } pub fn encode(&self) -> Bytes { use zenith_utils::bin_ser::LeSer; self.ser().unwrap().into() } } pub const SIZEOF_CHECKPOINT: usize = std::mem::size_of::<CheckPoint>(); impl CheckPoint { pub fn encode(&self) -> Bytes { use zenith_utils::bin_ser::LeSer; self.ser().unwrap().into() } pub fn decode(buf: &[u8]) -> Result<CheckPoint, anyhow::Error> { use zenith_utils::bin_ser::LeSer; Ok(CheckPoint::des(buf)?) } // Update next XID based on provided new_xid and stored epoch. // Next XID should be greater than new_xid. // Also take in account 32-bit wrap-around. pub fn update_next_xid(&mut self, xid: u32) { let xid = xid.wrapping_add(XID_CHECKPOINT_INTERVAL - 1) & !(XID_CHECKPOINT_INTERVAL - 1); let full_xid = self.nextXid.value; let new_xid = std::cmp::max(xid + 1, pg_constants::FIRST_NORMAL_TRANSACTION_ID); let old_xid = full_xid as u32; if new_xid.wrapping_sub(old_xid) as i32 > 0 { let mut epoch = full_xid >> 32; if new_xid < old_xid { // wrap-around epoch += 1; } self.nextXid = FullTransactionId { value: (epoch << 32) | new_xid as u64, }; } } } // // Generate new WAL segment with single XLOG_CHECKPOINT_SHUTDOWN record. // We need this segment to start compute node. // In order to minimize changes in Postgres core, we prefer to // provide WAL segment from which is can extract checkpoint record in standard way, // rather then implement some alternative mechanism. // pub fn generate_wal_segment(pg_control: &ControlFileData) -> Bytes { let mut seg_buf = BytesMut::with_capacity(pg_constants::WAL_SEGMENT_SIZE as usize); let hdr = XLogLongPageHeaderData { std: { XLogPageHeaderData { xlp_magic: XLOG_PAGE_MAGIC as u16, xlp_info: pg_constants::XLP_LONG_HEADER, xlp_tli: 1, // FIXME: always use Postgres timeline 1 xlp_pageaddr: pg_control.checkPoint - XLOG_SIZE_OF_XLOG_LONG_PHD as u64, xlp_rem_len: 0, ..Default::default() // Put 0 in padding fields. } }, xlp_sysid: pg_control.system_identifier, xlp_seg_size: pg_constants::WAL_SEGMENT_SIZE as u32, xlp_xlog_blcksz: XLOG_BLCKSZ as u32, }; let hdr_bytes = hdr.encode(); seg_buf.extend_from_slice(&hdr_bytes); let rec_hdr = XLogRecord { xl_tot_len: (XLOG_SIZE_OF_XLOG_RECORD + SIZE_OF_XLOG_RECORD_DATA_HEADER_SHORT + SIZEOF_CHECKPOINT) as u32, xl_xid: 0, //0 is for InvalidTransactionId xl_prev: 0, xl_info: pg_constants::XLOG_CHECKPOINT_SHUTDOWN, xl_rmid: pg_constants::RM_XLOG_ID, xl_crc: 0, ..Default::default() // Put 0 in padding fields. }; let mut rec_shord_hdr_bytes = BytesMut::new(); rec_shord_hdr_bytes.put_u8(pg_constants::XLR_BLOCK_ID_DATA_SHORT); rec_shord_hdr_bytes.put_u8(SIZEOF_CHECKPOINT as u8); let rec_bytes = rec_hdr.encode(); let checkpoint_bytes = pg_control.checkPointCopy.encode(); //calculate record checksum let mut crc = 0; crc = crc32c_append(crc, &rec_shord_hdr_bytes[..]); crc = crc32c_append(crc, &checkpoint_bytes[..]); crc = crc32c_append(crc, &rec_bytes[0..XLOG_RECORD_CRC_OFFS]); seg_buf.extend_from_slice(&rec_bytes[0..XLOG_RECORD_CRC_OFFS]); seg_buf.put_u32_le(crc); seg_buf.extend_from_slice(&rec_shord_hdr_bytes); seg_buf.extend_from_slice(&checkpoint_bytes); //zero out the rest of the file seg_buf.resize(pg_constants::WAL_SEGMENT_SIZE, 0); seg_buf.freeze() } #[cfg(test)] mod tests { use super::*; use regex::Regex; use std::{env, process::Command, str::FromStr}; // Run find_end_of_wal against file in test_wal dir // Ensure that it finds last record correctly #[test] pub fn test_find_end_of_wal() { // 1. Run initdb to generate some WAL let top_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(".."); let data_dir = top_path.join("test_output/test_find_end_of_wal"); let initdb_path = top_path.join("tmp_install/bin/initdb"); let lib_path = top_path.join("tmp_install/lib"); if data_dir.exists() { fs::remove_dir_all(&data_dir).unwrap(); } println!("Using initdb from '{}'", initdb_path.display()); println!("Data directory '{}'", data_dir.display()); let initdb_output = Command::new(initdb_path) .args(&["-D", data_dir.to_str().unwrap()]) .arg("--no-instructions") .arg("--no-sync") .env_clear() .env("LD_LIBRARY_PATH", &lib_path) .env("DYLD_LIBRARY_PATH", &lib_path) .output() .unwrap(); assert!(initdb_output.status.success()); // 2. Pick WAL generated by initdb let wal_dir = data_dir.join("pg_wal"); let wal_seg_size = 16 * 1024 * 1024; // 3. Check end_of_wal on non-partial WAL segment (we treat it as fully populated) let (wal_end, tli) = find_end_of_wal(&wal_dir, wal_seg_size, true, Lsn(0)).unwrap(); let wal_end = Lsn(wal_end); println!("wal_end={}, tli={}", wal_end, tli); assert_eq!(wal_end, "0/2000000".parse::<Lsn>().unwrap()); // 4. Get the actual end of WAL by pg_waldump let waldump_path = top_path.join("tmp_install/bin/pg_waldump"); let waldump_output = Command::new(waldump_path) .arg(wal_dir.join("000000010000000000000001")) .env_clear() .env("LD_LIBRARY_PATH", &lib_path) .env("DYLD_LIBRARY_PATH", &lib_path) .output() .unwrap(); let waldump_output = std::str::from_utf8(&waldump_output.stderr).unwrap(); println!("waldump_output = '{}'", &waldump_output); let re = Regex::new(r"invalid record length at (.+):").unwrap(); let caps = re.captures(waldump_output).unwrap(); let waldump_wal_end = Lsn::from_str(caps.get(1).unwrap().as_str()).unwrap(); // 5. Rename file to partial to actually find last valid lsn fs::rename( wal_dir.join("000000010000000000000001"), wal_dir.join("000000010000000000000001.partial"), ) .unwrap(); let (wal_end, tli) = find_end_of_wal(&wal_dir, wal_seg_size, true, Lsn(0)).unwrap(); let wal_end = Lsn(wal_end); println!("wal_end={}, tli={}", wal_end, tli); assert_eq!(wal_end, waldump_wal_end); } }
//! Local filesystem relish storage. //! //! Page server already stores layer data on the server, when freezing it. //! This storage serves a way to //! //! * test things locally simply //! * allow to compabre both binary sets //! * help validating the relish storage API use std::{ future::Future, path::{Path, PathBuf}, pin::Pin, }; use anyhow::{bail, Context}; use super::{strip_workspace_prefix, RelishStorage}; pub struct LocalFs { root: PathBuf, } impl LocalFs { /// Atetmpts to create local FS relish storage, also creates the directory provided, if not exists. pub fn new(root: PathBuf) -> anyhow::Result<Self> { if !root.exists() { std::fs::create_dir_all(&root).with_context(|| { format!( "Failed to create all directories in the given root path {}", root.display(), ) })?; } Ok(Self { root }) } fn resolve_in_storage(&self, path: &Path) -> anyhow::Result<PathBuf> { if path.is_relative() { Ok(self.root.join(path)) } else if path.starts_with(&self.root) { Ok(path.to_path_buf()) } else { bail!( "Path '{}' does not belong to the current storage", path.display() ) } } } #[async_trait::async_trait] impl RelishStorage for LocalFs { type RelishStoragePath = PathBuf; fn derive_destination( page_server_workdir: &Path, relish_local_path: &Path, ) -> anyhow::Result<Self::RelishStoragePath> { Ok(strip_workspace_prefix(page_server_workdir, relish_local_path)?.to_path_buf()) } async fn list_relishes(&self) -> anyhow::Result<Vec<Self::RelishStoragePath>> { Ok(get_all_files(&self.root).await?.into_iter().collect()) } async fn download_relish( &self, from: &Self::RelishStoragePath, to: &Path, ) -> anyhow::Result<()> { let file_path = self.resolve_in_storage(from)?; if file_path.exists() && file_path.is_file() { create_target_directory(to).await?; tokio::fs::copy(file_path, to).await?; Ok(()) } else { bail!( "File '{}' either does not exist or is not a file", file_path.display() ) } } async fn delete_relish(&self, path: &Self::RelishStoragePath) -> anyhow::Result<()> { let file_path = self.resolve_in_storage(path)?; if file_path.exists() && file_path.is_file() { Ok(tokio::fs::remove_file(file_path).await?) } else { bail!( "File '{}' either does not exist or is not a file", file_path.display() ) } } async fn upload_relish(&self, from: &Path, to: &Self::RelishStoragePath) -> anyhow::Result<()> { let target_file_path = self.resolve_in_storage(to)?; create_target_directory(&target_file_path).await?; tokio::fs::copy(&from, &target_file_path) .await .with_context(|| { format!( "Failed to upload relish '{}' to local storage", from.display(), ) })?; Ok(()) } } fn get_all_files<'a, P>( directory_path: P, ) -> Pin<Box<dyn Future<Output = anyhow::Result<Vec<PathBuf>>> + Send + Sync + 'a>> where P: AsRef<Path> + Send + Sync + 'a, { Box::pin(async move { let directory_path = directory_path.as_ref(); if directory_path.exists() { if directory_path.is_dir() { let mut paths = Vec::new(); let mut dir_contents = tokio::fs::read_dir(directory_path).await?; while let Some(dir_entry) = dir_contents.next_entry().await? { let file_type = dir_entry.file_type().await?; let entry_path = dir_entry.path(); if file_type.is_symlink() { log::debug!("{:?} us a symlink, skipping", entry_path) } else if file_type.is_dir() { paths.extend(get_all_files(entry_path).await?.into_iter()) } else { paths.push(dir_entry.path()); } } Ok(paths) } else { bail!("Path '{}' is not a directory", directory_path.display()) } } else { Ok(Vec::new()) } }) } async fn create_target_directory(target_file_path: &Path) -> anyhow::Result<()> { let target_dir = match target_file_path.parent() { Some(parent_dir) => parent_dir, None => bail!( "Relish path '{}' has no parent directory", target_file_path.display() ), }; if !target_dir.exists() { tokio::fs::create_dir_all(target_dir).await?; } Ok(()) }
use std::fs::File; use std::io::prelude::*; use std::env; fn main() -> std::io::Result<()> { let args: Vec<String> = env::args().collect(); let mut contents = String::new(); for arg in &args[1..] { let mut _fichier = match File::open(&arg){ Ok(_e) => { let mut _file = File::open(&arg)?.read_to_string(&mut contents)?; println!("DBGHSL: {}", contents); } Err(_e) => { println!("Le fichier n'existe pas") } }; } Ok(()) }
use std::io::Read; use rand::rngs::StdRng; use rand::{RngCore, SeedableRng}; pub struct Reader(StdRng); impl Read for Reader { fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { self.0.fill_bytes(buf); Ok(buf.len()) } } impl Reader { pub fn new(s: u64) -> Self { Self(StdRng::seed_from_u64(s)) } } pub fn read(buf: &mut [u8]) -> Result<(), String> { getrandom::getrandom(buf).map_err(|err| err.to_string()) }
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - SCT configuration register"] pub config: CONFIG, #[doc = "0x04 - SCT control register"] pub ctrl: CTRL, #[doc = "0x08 - SCT limit register"] pub limit: LIMIT, #[doc = "0x0c - SCT halt condition register"] pub halt: HALT, #[doc = "0x10 - SCT stop condition register"] pub stop: STOP, #[doc = "0x14 - SCT start condition register"] pub start: START, _reserved0: [u8; 40usize], #[doc = "0x40 - SCT counter register"] pub count: COUNT, #[doc = "0x44 - SCT state register"] pub state: STATE, #[doc = "0x48 - SCT input register"] pub input: INPUT, #[doc = "0x4c - SCT match/capture registers mode register"] pub regmode: REGMODE, #[doc = "0x50 - SCT output register"] pub output: OUTPUT, #[doc = "0x54 - SCT output counter direction control register"] pub outputdirctrl: OUTPUTDIRCTRL, #[doc = "0x58 - SCT conflict resolution register"] pub res: RES, _reserved1: [u8; 148usize], #[doc = "0xf0 - SCT event enable register"] pub even: EVEN, #[doc = "0xf4 - SCT event flag register"] pub evflag: EVFLAG, #[doc = "0xf8 - SCT conflict enable register"] pub conen: CONEN, #[doc = "0xfc - SCT conflict flag register"] pub conflag: CONFLAG, #[doc = "0x100 - SCT match value register of match channels 0 to 4; REGMOD0 to REGMODE4 = 0"] pub match_: [MATCH; 5], _reserved2: [u8; 236usize], #[doc = "0x200 - SCT match reload value register 0 to 4 REGMOD0 = 0 to REGMODE4 = 0"] pub matchrel: [MATCHREL; 5], _reserved3: [u8; 236usize], #[doc = "0x300 - SCT event state register 0"] pub ev0_state: EV0_STATE, #[doc = "0x304 - SCT event control register 0"] pub ev0_ctrl: EV0_CTRL, #[doc = "0x308 - SCT event state register 1"] pub ev1_state: EV1_STATE, #[doc = "0x30c - SCT event control register 1"] pub ev1_ctrl: EV1_CTRL, #[doc = "0x310 - SCT event state register 2"] pub ev2_state: EV2_STATE, #[doc = "0x314 - SCT event control register 2"] pub ev2_ctrl: EV2_CTRL, #[doc = "0x318 - SCT event state register 3"] pub ev3_state: EV3_STATE, #[doc = "0x31c - SCT event control register 3"] pub ev3_ctrl: EV3_CTRL, #[doc = "0x320 - SCT event state register 4"] pub ev4_state: EV4_STATE, #[doc = "0x324 - SCT event control register 4"] pub ev4_ctrl: EV4_CTRL, #[doc = "0x328 - SCT event state register 5"] pub ev5_state: EV5_STATE, #[doc = "0x32c - SCT event control register 5"] pub ev5_ctrl: EV5_CTRL, _reserved4: [u8; 464usize], #[doc = "0x500 - SCT output 0 set register"] pub out0_set: OUT0_SET, #[doc = "0x504 - SCT output 0 clear register"] pub out0_clr: OUT0_CLR, #[doc = "0x508 - SCT output 1 set register"] pub out1_set: OUT1_SET, #[doc = "0x50c - SCT output 1 clear register"] pub out1_clr: OUT1_CLR, #[doc = "0x510 - SCT output 2 set register"] pub out2_set: OUT2_SET, #[doc = "0x514 - SCT output 2 clear register"] pub out2_clr: OUT2_CLR, #[doc = "0x518 - SCT output 3 set register"] pub out3_set: OUT3_SET, #[doc = "0x51c - SCT output 3 clear register"] pub out3_clr: OUT3_CLR, } #[doc = "SCT configuration register"] pub struct CONFIG { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT configuration register"] pub mod config; #[doc = "SCT control register"] pub struct CTRL { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT control register"] pub mod ctrl; #[doc = "SCT limit register"] pub struct LIMIT { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT limit register"] pub mod limit; #[doc = "SCT halt condition register"] pub struct HALT { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT halt condition register"] pub mod halt; #[doc = "SCT stop condition register"] pub struct STOP { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT stop condition register"] pub mod stop; #[doc = "SCT start condition register"] pub struct START { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT start condition register"] pub mod start; #[doc = "SCT counter register"] pub struct COUNT { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT counter register"] pub mod count; #[doc = "SCT state register"] pub struct STATE { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT state register"] pub mod state; #[doc = "SCT input register"] pub struct INPUT { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT input register"] pub mod input; #[doc = "SCT match/capture registers mode register"] pub struct REGMODE { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT match/capture registers mode register"] pub mod regmode; #[doc = "SCT output register"] pub struct OUTPUT { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT output register"] pub mod output; #[doc = "SCT output counter direction control register"] pub struct OUTPUTDIRCTRL { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT output counter direction control register"] pub mod outputdirctrl; #[doc = "SCT conflict resolution register"] pub struct RES { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT conflict resolution register"] pub mod res; #[doc = "SCT event enable register"] pub struct EVEN { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT event enable register"] pub mod even; #[doc = "SCT event flag register"] pub struct EVFLAG { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT event flag register"] pub mod evflag; #[doc = "SCT conflict enable register"] pub struct CONEN { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT conflict enable register"] pub mod conen; #[doc = "SCT conflict flag register"] pub struct CONFLAG { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT conflict flag register"] pub mod conflag; #[doc = "SCT match value register of match channels 0 to 4; REGMOD0 to REGMODE4 = 0"] pub struct MATCH { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT match value register of match channels 0 to 4; REGMOD0 to REGMODE4 = 0"] pub mod match_; #[doc = "SCT capture register of capture channel 0 to 4; REGMOD0 to REGMODE4 = 1"] pub struct CAP { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT capture register of capture channel 0 to 4; REGMOD0 to REGMODE4 = 1"] pub mod cap; #[doc = "SCT match reload value register 0 to 4 REGMOD0 = 0 to REGMODE4 = 0"] pub struct MATCHREL { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT match reload value register 0 to 4 REGMOD0 = 0 to REGMODE4 = 0"] pub mod matchrel; #[doc = "SCT capture control register 0 to 4; REGMOD0 = 1 to REGMODE4 = 1"] pub struct CAPCTRL { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT capture control register 0 to 4; REGMOD0 = 1 to REGMODE4 = 1"] pub mod capctrl; #[doc = "SCT event state register 0"] pub struct EV0_STATE { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT event state register 0"] pub mod ev0_state; #[doc = "SCT event control register 0"] pub struct EV0_CTRL { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT event control register 0"] pub mod ev0_ctrl; #[doc = "SCT event state register 1"] pub struct EV1_STATE { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT event state register 1"] pub mod ev1_state; #[doc = "SCT event control register 1"] pub struct EV1_CTRL { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT event control register 1"] pub mod ev1_ctrl; #[doc = "SCT event state register 2"] pub struct EV2_STATE { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT event state register 2"] pub mod ev2_state; #[doc = "SCT event control register 2"] pub struct EV2_CTRL { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT event control register 2"] pub mod ev2_ctrl; #[doc = "SCT event state register 3"] pub struct EV3_STATE { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT event state register 3"] pub mod ev3_state; #[doc = "SCT event control register 3"] pub struct EV3_CTRL { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT event control register 3"] pub mod ev3_ctrl; #[doc = "SCT event state register 4"] pub struct EV4_STATE { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT event state register 4"] pub mod ev4_state; #[doc = "SCT event control register 4"] pub struct EV4_CTRL { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT event control register 4"] pub mod ev4_ctrl; #[doc = "SCT event state register 5"] pub struct EV5_STATE { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT event state register 5"] pub mod ev5_state; #[doc = "SCT event control register 5"] pub struct EV5_CTRL { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT event control register 5"] pub mod ev5_ctrl; #[doc = "SCT output 0 set register"] pub struct OUT0_SET { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT output 0 set register"] pub mod out0_set; #[doc = "SCT output 0 clear register"] pub struct OUT0_CLR { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT output 0 clear register"] pub mod out0_clr; #[doc = "SCT output 1 set register"] pub struct OUT1_SET { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT output 1 set register"] pub mod out1_set; #[doc = "SCT output 1 clear register"] pub struct OUT1_CLR { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT output 1 clear register"] pub mod out1_clr; #[doc = "SCT output 2 set register"] pub struct OUT2_SET { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT output 2 set register"] pub mod out2_set; #[doc = "SCT output 2 clear register"] pub struct OUT2_CLR { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT output 2 clear register"] pub mod out2_clr; #[doc = "SCT output 3 set register"] pub struct OUT3_SET { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT output 3 set register"] pub mod out3_set; #[doc = "SCT output 3 clear register"] pub struct OUT3_CLR { register: ::vcell::VolatileCell<u32>, } #[doc = "SCT output 3 clear register"] pub mod out3_clr;
use super::VarResult; use crate::ast::stat_expr_types::VarIndex; use crate::ast::syntax_type::SyntaxType; use crate::helper::ensure_srcs; use crate::helper::{ move_element, pine_ref_to_bool, pine_ref_to_color, pine_ref_to_f64, pine_ref_to_i64, pine_ref_to_string, }; use crate::runtime::context::{downcast_ctx, Ctx}; use crate::runtime::InputSrc; use crate::types::{ downcast_pf_ref, int2float, Arithmetic, Evaluate, EvaluateVal, Float, Int, PineRef, RuntimeErr, Series, }; #[derive(Debug, Clone, PartialEq)] struct AccDistVal { low_index: VarIndex, high_index: VarIndex, ad_history: Vec<Float>, is_init: bool, } impl AccDistVal { pub fn new() -> AccDistVal { AccDistVal { low_index: VarIndex::new(0, 0), high_index: VarIndex::new(0, 0), ad_history: vec![], is_init: false, } } } // ref to https://www.investopedia.com/terms/a/accumulationdistribution.asp // CMFV=Current money flow volume = ((Pc - Pl) - (Ph - Pc)) / (Ph - Pl) * V impl<'a> EvaluateVal<'a> for AccDistVal { fn custom_name(&self) -> &str { "hl2" } fn call(&mut self, ctx: &mut dyn Ctx<'a>) -> Result<PineRef<'a>, RuntimeErr> { ensure_srcs(ctx, vec!["low", "high"], |indexs| { self.low_index = indexs[0]; self.high_index = indexs[1]; }); let low = pine_ref_to_f64(ctx.get_var(self.low_index).clone()); let high = pine_ref_to_f64(ctx.get_var(self.high_index).clone()); let res = high.add(low).div(Some(2f64)); self.ad_history.push(res); Ok(PineRef::new_rc(Series::from(res))) } fn back(&mut self, _ctx: &mut dyn Ctx<'a>) -> Result<(), RuntimeErr> { self.ad_history.pop(); Ok(()) } // fn run(&mut self, _ctx: &mut dyn Ctx<'a>) -> Result<(), RuntimeErr> { // Ok(()) // } fn copy(&self) -> Box<dyn EvaluateVal<'a>> { Box::new(self.clone()) } } pub const VAR_NAME: &'static str = "hl2"; pub fn declare_var<'a>() -> VarResult<'a> { let value = PineRef::new(Evaluate::new(Box::new(AccDistVal::new()))); let syntax_type = SyntaxType::float_series(); VarResult::new(value, syntax_type, VAR_NAME) } #[cfg(test)] mod tests { use super::*; use crate::ast::syntax_type::SyntaxType; use crate::runtime::VarOperate; use crate::runtime::{AnySeries, NoneCallback}; use crate::types::Series; use crate::{LibInfo, PineParser, PineRunner}; #[test] fn accdist_test() { let lib_info = LibInfo::new( vec![declare_var()], vec![ ("high", SyntaxType::float_series()), ("low", SyntaxType::float_series()), ], ); let src = "m = hl2"; let blk = PineParser::new(src, &lib_info).parse_blk().unwrap(); let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback()); runner .run( &vec![ ( "high", AnySeries::from_float_vec(vec![Some(15f64), Some(22f64)]), ), ( "low", AnySeries::from_float_vec(vec![Some(1f64), Some(2f64)]), ), ], None, ) .unwrap(); assert_eq!( runner.get_context().get_var(VarIndex::new(0, 0)), &Some(PineRef::new(Series::from_vec(vec![ Some(8f64), Some(12f64) ]))) ); } }
//! ECDSA tests mod p256; mod p384; #[macro_export] macro_rules! ecdsa_tests { ($signing_key:ty, $verifying_key:ty, $test_vectors:expr) => { fn example_signing_key() -> $signing_key { let vector = $test_vectors[0]; // Add SEC1 tag byte let mut pk = vec![0x04]; pk.extend_from_slice(vector.pk); <$signing_key>::from_keypair_bytes(vector.sk, &pk).unwrap() } #[test] fn sign_and_verify() { let signing_key = example_signing_key(); let msg = $test_vectors[0].msg; let sig = signing_key.sign(msg); let verifying_key = signing_key.verifying_key(); assert!(verifying_key.verify(msg, &sig).is_ok()); } #[test] fn verify_nist_test_vectors() { for vector in $test_vectors { let verifying_key = <$verifying_key>::new(vector.pk).unwrap(); let sig = Signature::try_from(vector.sig).unwrap(); assert!(verifying_key.verify(vector.msg, &sig).is_ok()); } } #[test] fn rejects_tweaked_nist_test_vectors() { for vector in $test_vectors { let mut tweaked_sig = Vec::from(vector.sig); *tweaked_sig.iter_mut().last().unwrap() ^= 0x42; let verifying_key = <$verifying_key>::new(vector.pk).unwrap(); let sig = Signature::try_from(tweaked_sig.as_slice()).unwrap(); assert!(verifying_key.verify(vector.msg, &sig).is_err()); } } }; }
use crate::RpcContext; use anyhow::{anyhow, Context}; use pathfinder_common::BlockId; #[derive(serde::Deserialize, Debug, PartialEq, Eq)] pub struct GetStateUpdateInput { block_id: BlockId, } crate::error::generate_rpc_error_subset!(GetStateUpdateError: BlockNotFound); pub async fn get_state_update( context: RpcContext, input: GetStateUpdateInput, ) -> Result<types::StateUpdate, GetStateUpdateError> { let block_id = match input.block_id { BlockId::Pending => { match &context .pending_data .ok_or_else(|| anyhow!("Pending data not supported in this configuration"))? .state_update() .await { Some(update) => { let update = update.as_ref().clone().into(); return Ok(update); } None => return Err(GetStateUpdateError::BlockNotFound), } } other => other.try_into().expect("Only pending cast should fail"), }; let storage = context.storage.clone(); let span = tracing::Span::current(); let jh = tokio::task::spawn_blocking(move || { let _g = span.enter(); let mut db = storage .connection() .context("Opening database connection")?; let tx = db.transaction().context("Creating database transaction")?; get_state_update_from_storage(&tx, block_id) }); jh.await.context("Database read panic or shutting down")? } fn get_state_update_from_storage( tx: &pathfinder_storage::Transaction<'_>, block: pathfinder_storage::BlockId, ) -> Result<types::StateUpdate, GetStateUpdateError> { let state_update = tx .state_update(block) .context("Fetching state diff")? .ok_or(GetStateUpdateError::BlockNotFound)?; Ok(state_update.into()) } mod types { use crate::felt::{RpcFelt, RpcFelt251}; use pathfinder_common::state_update::ContractClassUpdate; use pathfinder_common::{ BlockHash, CasmHash, ClassHash, ContractAddress, ContractNonce, SierraHash, StateCommitment, StorageAddress, StorageValue, }; use serde::Serialize; use serde_with::skip_serializing_none; #[serde_with::serde_as] #[skip_serializing_none] #[derive(Clone, Debug, Serialize, PartialEq, Eq)] #[cfg_attr(any(test, feature = "rpc-full-serde"), derive(serde::Deserialize))] #[serde(deny_unknown_fields)] pub struct StateUpdate { /// None for `pending` #[serde(default)] #[serde_as(as = "Option<RpcFelt>")] pub block_hash: Option<BlockHash>, /// None for `pending` #[serde(default)] #[serde_as(as = "Option<RpcFelt>")] pub new_root: Option<StateCommitment>, #[serde_as(as = "RpcFelt")] pub old_root: StateCommitment, pub state_diff: StateDiff, } #[cfg(test)] impl StateUpdate { // Sorts its vectors so that they can be equated. pub fn sort(&mut self) { self.state_diff .deployed_contracts .sort_by_key(|x| x.address); self.state_diff .declared_classes .sort_by_key(|x| x.class_hash); self.state_diff .replaced_classes .sort_by_key(|x| x.contract_address); self.state_diff.deprecated_declared_classes.sort(); self.state_diff.nonces.sort_by_key(|x| x.contract_address); self.state_diff.storage_diffs.sort_by_key(|x| x.address); self.state_diff.storage_diffs.iter_mut().for_each(|x| { x.storage_entries.sort_by_key(|x| x.key); }); } } impl From<pathfinder_common::StateUpdate> for StateUpdate { fn from(value: pathfinder_common::StateUpdate) -> Self { let mut storage_diffs = Vec::new(); let mut deployed_contracts = Vec::new(); let mut replaced_classes = Vec::new(); let mut nonces = Vec::new(); for (contract_address, update) in value.contract_updates { if let Some(nonce) = update.nonce { nonces.push(Nonce { contract_address, nonce, }); } match update.class { Some(ContractClassUpdate::Deploy(class_hash)) => { deployed_contracts.push(DeployedContract { address: contract_address, class_hash, }) } Some(ContractClassUpdate::Replace(class_hash)) => { replaced_classes.push(ReplacedClass { contract_address, class_hash, }) } None => {} } let storage_entries = update .storage .into_iter() .map(|(key, value)| StorageEntry { key, value }) .collect(); storage_diffs.push(StorageDiff { address: contract_address, storage_entries, }); } for (address, update) in value.system_contract_updates { let storage_entries = update .storage .into_iter() .map(|(key, value)| StorageEntry { key, value }) .collect(); storage_diffs.push(StorageDiff { address, storage_entries, }); } let declared_classes = value .declared_sierra_classes .into_iter() .map(|(class_hash, compiled_class_hash)| DeclaredSierraClass { class_hash, compiled_class_hash, }) .collect(); let deprecated_declared_classes = value.declared_cairo_classes.into_iter().collect(); let state_diff = StateDiff { storage_diffs, deprecated_declared_classes, declared_classes, deployed_contracts, replaced_classes, nonces, }; let block_hash = match value.block_hash { BlockHash::ZERO => None, other => Some(other), }; let new_root = match value.state_commitment { StateCommitment::ZERO => None, other => Some(other), }; StateUpdate { block_hash, new_root, old_root: value.parent_state_commitment, state_diff, } } } /// L2 state diff. #[serde_with::serde_as] #[derive(Clone, Debug, Serialize, PartialEq, Eq)] #[cfg_attr(any(test, feature = "rpc-full-serde"), derive(serde::Deserialize))] #[serde(deny_unknown_fields)] pub struct StateDiff { pub storage_diffs: Vec<StorageDiff>, #[serde_as(as = "Vec<RpcFelt>")] pub deprecated_declared_classes: Vec<ClassHash>, pub declared_classes: Vec<DeclaredSierraClass>, pub deployed_contracts: Vec<DeployedContract>, pub replaced_classes: Vec<ReplacedClass>, pub nonces: Vec<Nonce>, } /// L2 storage diff of a contract. #[serde_with::serde_as] #[derive(Clone, Debug, Serialize, PartialEq, Eq, PartialOrd, Ord)] #[cfg_attr(any(test, feature = "rpc-full-serde"), derive(serde::Deserialize))] #[serde(deny_unknown_fields)] pub struct StorageDiff { #[serde_as(as = "RpcFelt251")] pub address: ContractAddress, pub storage_entries: Vec<StorageEntry>, } /// A key-value entry of a storage diff. #[serde_with::serde_as] #[derive(Clone, Debug, Serialize, PartialEq, Eq, PartialOrd, Ord)] #[cfg_attr(any(test, feature = "rpc-full-serde"), derive(serde::Deserialize))] #[serde(deny_unknown_fields)] pub struct StorageEntry { #[serde_as(as = "RpcFelt251")] pub key: StorageAddress, #[serde_as(as = "RpcFelt")] pub value: StorageValue, } impl From<starknet_gateway_types::reply::state_update::StorageDiff> for StorageEntry { fn from(d: starknet_gateway_types::reply::state_update::StorageDiff) -> Self { Self { key: d.key, value: d.value, } } } /// L2 state diff declared Sierra class item. #[serde_with::serde_as] #[derive(Clone, Debug, Serialize, PartialEq, Eq)] #[cfg_attr(any(test, feature = "rpc-full-serde"), derive(serde::Deserialize))] #[serde(deny_unknown_fields)] pub struct DeclaredSierraClass { #[serde_as(as = "RpcFelt")] pub class_hash: SierraHash, #[serde_as(as = "RpcFelt")] pub compiled_class_hash: CasmHash, } /// L2 state diff deployed contract item. #[serde_with::serde_as] #[derive(Clone, Debug, Serialize, PartialEq, Eq)] #[cfg_attr(any(test, feature = "rpc-full-serde"), derive(serde::Deserialize))] #[serde(deny_unknown_fields)] pub struct DeployedContract { #[serde_as(as = "RpcFelt251")] pub address: ContractAddress, #[serde_as(as = "RpcFelt")] pub class_hash: ClassHash, } /// L2 state diff replaced class item. #[serde_with::serde_as] #[derive(Clone, Debug, Serialize, PartialEq, Eq)] #[cfg_attr(any(test, feature = "rpc-full-serde"), derive(serde::Deserialize))] #[serde(deny_unknown_fields)] pub struct ReplacedClass { #[serde_as(as = "RpcFelt251")] pub contract_address: ContractAddress, #[serde_as(as = "RpcFelt")] pub class_hash: ClassHash, } /// L2 state diff nonce item. #[serde_with::serde_as] #[derive(Clone, Debug, Serialize, PartialEq, Eq)] #[cfg_attr(any(test, feature = "rpc-full-serde"), derive(serde::Deserialize))] #[serde(deny_unknown_fields)] pub struct Nonce { #[serde_as(as = "RpcFelt251")] pub contract_address: ContractAddress, #[serde_as(as = "RpcFelt")] pub nonce: ContractNonce, } #[cfg(test)] mod tests { use super::*; use pathfinder_common::macro_prelude::*; #[test] fn receipt() { let state_update = StateUpdate { block_hash: Some(block_hash!("0xdeadbeef")), new_root: Some(state_commitment!("0x1")), old_root: state_commitment!("0x2"), state_diff: StateDiff { storage_diffs: vec![StorageDiff { address: contract_address!("0xadc"), storage_entries: vec![StorageEntry { key: storage_address!("0xf0"), value: storage_value!("0x55"), }], }], deprecated_declared_classes: vec![class_hash!("0xcdef"), class_hash!("0xcdee")], declared_classes: vec![DeclaredSierraClass { class_hash: sierra_hash!("0xabcd"), compiled_class_hash: casm_hash!("0xdcba"), }], deployed_contracts: vec![DeployedContract { address: contract_address!("0xadd"), class_hash: class_hash!("0xcdef"), }], replaced_classes: vec![ReplacedClass { contract_address: contract_address!("0xcad"), class_hash: class_hash!("0xdac"), }], nonces: vec![Nonce { contract_address: contract_address!("0xca"), nonce: contract_nonce!("0x404ce"), }], }, }; let data = vec![ state_update.clone(), StateUpdate { block_hash: None, ..state_update }, ]; let fixture = include_str!("../../../fixtures/0.50.0/state_update.json").replace([' ', '\n'], ""); pretty_assertions::assert_eq!(serde_json::to_string(&data).unwrap(), fixture); pretty_assertions::assert_eq!( serde_json::from_str::<Vec<StateUpdate>>(&fixture).unwrap(), data ); } } } #[cfg(test)] mod tests { use super::types::StateUpdate; use super::*; use assert_matches::assert_matches; use jsonrpsee::types::Params; use pathfinder_common::macro_prelude::*; use pathfinder_common::BlockNumber; use starknet_gateway_types::pending::PendingData; #[test] fn parsing() { let number = BlockId::Number(BlockNumber::new_or_panic(123)); let hash = BlockId::Hash(block_hash!("0xbeef")); [ (r#"["pending"]"#, BlockId::Pending), (r#"{"block_id": "pending"}"#, BlockId::Pending), (r#"["latest"]"#, BlockId::Latest), (r#"{"block_id": "latest"}"#, BlockId::Latest), (r#"[{"block_number":123}]"#, number), (r#"{"block_id": {"block_number":123}}"#, number), (r#"[{"block_hash": "0xbeef"}]"#, hash), (r#"{"block_id": {"block_hash": "0xbeef"}}"#, hash), ] .into_iter() .enumerate() .for_each(|(i, (input, expected))| { let actual = Params::new(Some(input)) .parse::<GetStateUpdateInput>() .unwrap_or_else(|error| panic!("test case {i}: {input}, {error}")); assert_eq!( actual, GetStateUpdateInput { block_id: expected }, "test case {i}: {input}" ); }); } type TestCaseHandler = Box<dyn Fn(usize, &Result<types::StateUpdate, GetStateUpdateError>)>; /// Add some dummy state updates to the context for testing fn context_with_state_updates() -> (Vec<types::StateUpdate>, RpcContext) { use pathfinder_common::ChainId; let storage = pathfinder_storage::Storage::in_memory().unwrap(); let state_updates = pathfinder_storage::fake::with_n_blocks(&storage, 3) .into_iter() .map(|(_, _, x)| x.into()) .collect(); let sync_state = std::sync::Arc::new(crate::SyncState::default()); let sequencer = starknet_gateway_client::Client::testnet(); let context = RpcContext::new(storage, sync_state, ChainId::TESTNET, sequencer); (state_updates, context) } /// Execute a single test case and check its outcome. async fn check(test_case_idx: usize, test_case: &(RpcContext, BlockId, TestCaseHandler)) { let (context, block_id, f) = test_case; let mut result = get_state_update( context.clone(), GetStateUpdateInput { block_id: *block_id, }, ) .await; if let Ok(r) = result.as_mut() { r.sort(); } f(test_case_idx, &result); } /// Common assertion type for most of the test cases fn assert_ok(mut expected: types::StateUpdate) -> TestCaseHandler { expected.sort(); Box::new(move |i: usize, result| { assert_matches!(result, Ok(actual) => pretty_assertions::assert_eq!( *actual, expected, "test case {i}" ), "test case {i}"); }) } impl PartialEq for GetStateUpdateError { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Internal(l), Self::Internal(r)) => l.to_string() == r.to_string(), _ => core::mem::discriminant(self) == core::mem::discriminant(other), } } } /// Common assertion type for most of the error paths fn assert_error(expected: GetStateUpdateError) -> TestCaseHandler { Box::new(move |i: usize, result| { assert_matches!(result, Err(error) => assert_eq!(*error, expected, "test case {i}"), "test case {i}"); }) } #[tokio::test] async fn happy_paths_and_major_errors() { let (in_storage, ctx) = context_with_state_updates(); let ctx_with_pending_empty = ctx.clone().with_pending_data(PendingData::default()); let cases: &[(RpcContext, BlockId, TestCaseHandler)] = &[ // Successful ( ctx.clone(), BlockId::Latest, assert_ok(in_storage[2].clone()), ), ( ctx.clone(), BlockId::Number(BlockNumber::GENESIS), assert_ok(in_storage[0].clone()), ), ( ctx.clone(), BlockId::Hash(in_storage[0].block_hash.unwrap()), assert_ok(in_storage[0].clone()), ), // Errors ( ctx.clone(), BlockId::Number(BlockNumber::new_or_panic(9999)), assert_error(GetStateUpdateError::BlockNotFound), ), ( ctx.clone(), BlockId::Hash(block_hash_bytes!(b"non-existent")), assert_error(GetStateUpdateError::BlockNotFound), ), ( // Pending is disabled for this context ctx, BlockId::Pending, assert_error(GetStateUpdateError::Internal(anyhow!( "Pending data not supported in this configuration" ))), ), ( ctx_with_pending_empty, BlockId::Pending, assert_error(GetStateUpdateError::BlockNotFound), ), ]; for (i, test_case) in cases.iter().enumerate() { check(i, test_case).await; } } #[tokio::test] async fn pending() { let context = RpcContext::for_tests_with_pending().await; let input = GetStateUpdateInput { block_id: BlockId::Pending, }; let expected: StateUpdate = context .pending_data .as_ref() .unwrap() .state_update() .await .unwrap() .as_ref() .to_owned() .into(); let result = get_state_update(context, input).await.unwrap(); pretty_assertions::assert_eq!(result, expected); } }
use ash::extensions::{ext, khr}; use ash::version::{EntryV1_0, InstanceV1_0}; use ash::{self, vk}; use lazy_static::lazy_static; use parking_lot::{RwLock, RwLockReadGuard}; use std::ffi::CStr; use std::fmt; use std::mem; use std::sync::Arc; use crate::imp::{debug, AdapterInner, InstanceExt, InstanceInner, SurfaceInner}; use crate::{Adapter, AdapterOptions, Error, Instance, Surface, SurfaceDescriptor}; use raw_window_handle::HasRawWindowHandle; use std::fmt::Debug; use std::sync::atomic::Ordering; lazy_static! { static ref ENTRY: RwLock<Result<ash::Entry, Error>> = { unsafe { extern "C" fn unload() { let mut entry_guard = ENTRY.write(); *entry_guard = Err(Error::from(String::from("Vulkan library unloaded"))); } libc::atexit(unload); RwLock::new(ash::Entry::new().map_err(Into::into)) } }; } impl Instance { pub fn new() -> Result<Instance, Error> { let inner = InstanceInner::new()?; Ok(inner.into()) } pub fn get_adapter(&self, options: AdapterOptions) -> Result<Adapter, Error> { let adapter = AdapterInner::new(self.inner.clone(), options)?; Ok(adapter.into()) } pub fn create_surface(&self, descriptor: &SurfaceDescriptor) -> Result<Surface, Error> { let surface = SurfaceInner::new(self.inner.clone(), descriptor)?; Ok(surface.into()) } pub fn create_surface_raw<W: HasRawWindowHandle>(&self, window: &W) -> Result<Surface, Error> { let surface = SurfaceInner::from_raw_window_handle(self.inner.clone(), window.raw_window_handle())?; Ok(surface.into()) } } impl InstanceInner { #[rustfmt::skip] fn new() -> Result<InstanceInner, Error> { let init_debug_report = debug::TEST_VALIDATION_HOOK.load(Ordering::Acquire); unsafe { let entry_guard: RwLockReadGuard<Result<ash::Entry, Error>> = ENTRY.read(); let entry: &ash::Entry = entry_guard.as_ref()?; let mut extension_names = vec![]; let extension_properties = entry.enumerate_instance_extension_properties()?; for p in extension_properties.iter() { let mut include_extension = false; let name = CStr::from_ptr(p.extension_name.as_ptr()); let name_cow = name.to_string_lossy(); log::trace!("found instance extension: {}", name_cow); if name_cow.ends_with("surface") { include_extension = true; } if name_cow == "VK_EXT_debug_report" && init_debug_report { include_extension = true; } if name_cow == "VK_EXT_debug_utils" { include_extension = true; } if include_extension { log::debug!("requesting extension support: {}", name_cow); extension_names.push(name.to_owned()); } } let instance_layer_properties = entry.enumerate_instance_layer_properties()?; for p in instance_layer_properties.iter() { let name = CStr::from_ptr(p.layer_name.as_ptr()); log::trace!("found instance layer: {}", name.to_string_lossy()); } let app_info = vk::ApplicationInfo::builder() .api_version(ash::vk_make_version!(1, 0, 0)); let layer_names = vec![ #[cfg(debug_assertions)] c_str!("VK_LAYER_LUNARG_standard_validation") ]; for layer_name in layer_names.iter() { let requested_layer_name = CStr::from_ptr(*layer_name); let is_available = instance_layer_properties.iter().any(|p| { let name = CStr::from_ptr(p.layer_name.as_ptr()); name == requested_layer_name }); if !is_available { log::error!("requested layer unavailable: {:?}", requested_layer_name.to_string_lossy()); } } let extension_names_ptrs: Vec<_> = extension_names.iter().map(|name| name.as_ptr()).collect(); let create_info = vk::InstanceCreateInfo::builder() .application_info(&app_info) .enabled_extension_names(&extension_names_ptrs) .enabled_layer_names(&layer_names); let raw = entry.create_instance(&create_info, None)?; let surface = khr::Surface::new(entry, &raw); #[cfg(windows)] let surface_win32 = khr::Win32Surface::new(entry, &raw); #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))] let surface_xlib = khr::XlibSurface::new(entry, &raw); #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))] let surface_xcb = khr::XcbSurface::new(entry, &raw); #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))] let surface_wayland = khr::WaylandSurface::new(entry, &raw); #[cfg(all(unix, target_os = "macos"))] let surface_macos= ash::extensions::mvk::MacOSSurface::new(entry, &raw); let debug_utils = ext::DebugUtils::new(entry, &raw); let debug_report = ext::DebugReport::new(entry, &raw); let debug_report_callback = if init_debug_report { let debug_report_create_info = vk::DebugReportCallbackCreateInfoEXT::builder() .flags(vk::DebugReportFlagsEXT::ERROR | vk::DebugReportFlagsEXT::WARNING | vk::DebugReportFlagsEXT::PERFORMANCE_WARNING) .user_data(mem::transmute(raw.handle())) .pfn_callback(Some(debug::debug_report_callback_test)); Some(debug_report.create_debug_report_callback(&debug_report_create_info, None)?) } else { None }; let raw_ext = InstanceExt { surface, #[cfg(windows)] surface_win32, #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))] surface_xlib, #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))] surface_xcb, #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))] surface_wayland, #[cfg(all(unix, target_os = "macos"))] surface_macos, debug_utils, debug_report, }; Ok(InstanceInner { raw, raw_ext, extension_properties, debug_report_callback }) } } pub fn has_extension(&self, name: &str) -> bool { for extension_properties in self.extension_properties.iter() { let ext_name = unsafe { CStr::from_ptr(extension_properties.extension_name.as_ptr()) }; if name == ext_name.to_str().unwrap() { return true; } } false } } impl Into<Instance> for InstanceInner { fn into(self) -> Instance { Instance { inner: Arc::new(self) } } } impl Debug for InstanceInner { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{:?}", self.raw.handle()) } } impl Drop for InstanceInner { fn drop(&mut self) { unsafe { if let Some(debug_report_callback) = self.debug_report_callback { self.raw_ext .debug_report .destroy_debug_report_callback(debug_report_callback, None); } self.raw.destroy_instance(None); } } }
#[derive(Clone, Copy)] pub enum Controller { Invalid, Auto, Handheld, Player(u8), } pub enum Key { None, A = 1, B = 2, X = 4, Y = 8, LStick = 16, RStick = 32, L = 64, R = 128, ZL = 256, ZR = 512, Plus = 1024, Minus = 2048, DPadRight = 16384, DPadUp = 8192, DPadDown = 32768, DPadLeft = 4096, } pub enum JoyConHoldMode { Default, Horizontal, } fn ctrlid_to_controller(id: ::libnx::HidControllerID) -> Controller { match id { ::libnx::HidControllerID_CONTROLLER_PLAYER_1 => Controller::Player(1), ::libnx::HidControllerID_CONTROLLER_PLAYER_2 => Controller::Player(2), ::libnx::HidControllerID_CONTROLLER_PLAYER_3 => Controller::Player(3), ::libnx::HidControllerID_CONTROLLER_PLAYER_4 => Controller::Player(4), ::libnx::HidControllerID_CONTROLLER_PLAYER_5 => Controller::Player(5), ::libnx::HidControllerID_CONTROLLER_PLAYER_6 => Controller::Player(6), ::libnx::HidControllerID_CONTROLLER_PLAYER_7 => Controller::Player(7), ::libnx::HidControllerID_CONTROLLER_PLAYER_8 => Controller::Player(8), ::libnx::HidControllerID_CONTROLLER_HANDHELD => Controller::Handheld, ::libnx::HidControllerID_CONTROLLER_P1_AUTO => Controller::Auto, _ => Controller::Invalid, } } fn controller_to_ctrlid(id: Controller) -> ::libnx::HidControllerID { match id { Controller::Player(1) => ::libnx::HidControllerID_CONTROLLER_PLAYER_1, Controller::Player(2) => ::libnx::HidControllerID_CONTROLLER_PLAYER_2, Controller::Player(3) => ::libnx::HidControllerID_CONTROLLER_PLAYER_3, Controller::Player(4) => ::libnx::HidControllerID_CONTROLLER_PLAYER_4, Controller::Player(5) => ::libnx::HidControllerID_CONTROLLER_PLAYER_5, Controller::Player(6) => ::libnx::HidControllerID_CONTROLLER_PLAYER_6, Controller::Player(7) => ::libnx::HidControllerID_CONTROLLER_PLAYER_7, Controller::Player(8) => ::libnx::HidControllerID_CONTROLLER_PLAYER_8, Controller::Handheld => ::libnx::HidControllerID_CONTROLLER_HANDHELD, Controller::Auto => ::libnx::HidControllerID_CONTROLLER_P1_AUTO, _ => ::libnx::HidControllerID_CONTROLLER_UNKNOWN, } } pub fn is_controller_connected(ctrl: Controller) -> bool { unsafe { ::libnx::hidIsControllerConnected(controller_to_ctrlid(ctrl)) } } pub fn flush() { unsafe { ::libnx::hidScanInput(); } } pub fn input_down(ctrl: Controller) -> u64 { flush(); unsafe { ::libnx::hidKeysDown(controller_to_ctrlid(ctrl)) } } pub fn input_up(ctrl: Controller) -> u64 { unsafe { flush(); ::libnx::hidKeysUp(controller_to_ctrlid(ctrl)) } } pub fn input_held(ctrl: Controller) -> u64 { unsafe { flush(); ::libnx::hidKeysHeld(controller_to_ctrlid(ctrl)) } } pub fn get_touch_count() -> u32 { unsafe { ::libnx::hidTouchCount() } } pub fn get_touch_coords(index: u32) -> (u32, u32) { flush(); unsafe { let mut tch: ::libnx::touchPosition = std::mem::zeroed(); ::libnx::hidTouchRead(&mut tch, index); (tch.px, tch.py) } }
pub fn zeros1d(size: u32) -> Vec<f64> { vec![0.0 size as usize] } pub fn zeros2d(size1: u32, size2: u32) -> Vec<Vec<f64>> { vec![vec![0.0; size2 as usize]; size1 as usize] }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::_3_GENA { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = "Possible values of the field `PWM_3_GENA_ACTZERO`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENA_ACTZEROR { #[doc = "Do nothing"] PWM_3_GENA_ACTZERO_NONE, #[doc = "Invert pwmA"] PWM_3_GENA_ACTZERO_INV, #[doc = "Drive pwmA Low"] PWM_3_GENA_ACTZERO_ZERO, #[doc = "Drive pwmA High"] PWM_3_GENA_ACTZERO_ONE, } impl PWM_3_GENA_ACTZEROR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { PWM_3_GENA_ACTZEROR::PWM_3_GENA_ACTZERO_NONE => 0, PWM_3_GENA_ACTZEROR::PWM_3_GENA_ACTZERO_INV => 1, PWM_3_GENA_ACTZEROR::PWM_3_GENA_ACTZERO_ZERO => 2, PWM_3_GENA_ACTZEROR::PWM_3_GENA_ACTZERO_ONE => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> PWM_3_GENA_ACTZEROR { match value { 0 => PWM_3_GENA_ACTZEROR::PWM_3_GENA_ACTZERO_NONE, 1 => PWM_3_GENA_ACTZEROR::PWM_3_GENA_ACTZERO_INV, 2 => PWM_3_GENA_ACTZEROR::PWM_3_GENA_ACTZERO_ZERO, 3 => PWM_3_GENA_ACTZEROR::PWM_3_GENA_ACTZERO_ONE, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTZERO_NONE`"] #[inline(always)] pub fn is_pwm_3_gena_actzero_none(&self) -> bool { *self == PWM_3_GENA_ACTZEROR::PWM_3_GENA_ACTZERO_NONE } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTZERO_INV`"] #[inline(always)] pub fn is_pwm_3_gena_actzero_inv(&self) -> bool { *self == PWM_3_GENA_ACTZEROR::PWM_3_GENA_ACTZERO_INV } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTZERO_ZERO`"] #[inline(always)] pub fn is_pwm_3_gena_actzero_zero(&self) -> bool { *self == PWM_3_GENA_ACTZEROR::PWM_3_GENA_ACTZERO_ZERO } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTZERO_ONE`"] #[inline(always)] pub fn is_pwm_3_gena_actzero_one(&self) -> bool { *self == PWM_3_GENA_ACTZEROR::PWM_3_GENA_ACTZERO_ONE } } #[doc = "Values that can be written to the field `PWM_3_GENA_ACTZERO`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENA_ACTZEROW { #[doc = "Do nothing"] PWM_3_GENA_ACTZERO_NONE, #[doc = "Invert pwmA"] PWM_3_GENA_ACTZERO_INV, #[doc = "Drive pwmA Low"] PWM_3_GENA_ACTZERO_ZERO, #[doc = "Drive pwmA High"] PWM_3_GENA_ACTZERO_ONE, } impl PWM_3_GENA_ACTZEROW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { PWM_3_GENA_ACTZEROW::PWM_3_GENA_ACTZERO_NONE => 0, PWM_3_GENA_ACTZEROW::PWM_3_GENA_ACTZERO_INV => 1, PWM_3_GENA_ACTZEROW::PWM_3_GENA_ACTZERO_ZERO => 2, PWM_3_GENA_ACTZEROW::PWM_3_GENA_ACTZERO_ONE => 3, } } } #[doc = r"Proxy"] pub struct _PWM_3_GENA_ACTZEROW<'a> { w: &'a mut W, } impl<'a> _PWM_3_GENA_ACTZEROW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PWM_3_GENA_ACTZEROW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Do nothing"] #[inline(always)] pub fn pwm_3_gena_actzero_none(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTZEROW::PWM_3_GENA_ACTZERO_NONE) } #[doc = "Invert pwmA"] #[inline(always)] pub fn pwm_3_gena_actzero_inv(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTZEROW::PWM_3_GENA_ACTZERO_INV) } #[doc = "Drive pwmA Low"] #[inline(always)] pub fn pwm_3_gena_actzero_zero(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTZEROW::PWM_3_GENA_ACTZERO_ZERO) } #[doc = "Drive pwmA High"] #[inline(always)] pub fn pwm_3_gena_actzero_one(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTZEROW::PWM_3_GENA_ACTZERO_ONE) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 0); self.w.bits |= ((value as u32) & 3) << 0; self.w } } #[doc = "Possible values of the field `PWM_3_GENA_ACTLOAD`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENA_ACTLOADR { #[doc = "Do nothing"] PWM_3_GENA_ACTLOAD_NONE, #[doc = "Invert pwmA"] PWM_3_GENA_ACTLOAD_INV, #[doc = "Drive pwmA Low"] PWM_3_GENA_ACTLOAD_ZERO, #[doc = "Drive pwmA High"] PWM_3_GENA_ACTLOAD_ONE, } impl PWM_3_GENA_ACTLOADR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { PWM_3_GENA_ACTLOADR::PWM_3_GENA_ACTLOAD_NONE => 0, PWM_3_GENA_ACTLOADR::PWM_3_GENA_ACTLOAD_INV => 1, PWM_3_GENA_ACTLOADR::PWM_3_GENA_ACTLOAD_ZERO => 2, PWM_3_GENA_ACTLOADR::PWM_3_GENA_ACTLOAD_ONE => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> PWM_3_GENA_ACTLOADR { match value { 0 => PWM_3_GENA_ACTLOADR::PWM_3_GENA_ACTLOAD_NONE, 1 => PWM_3_GENA_ACTLOADR::PWM_3_GENA_ACTLOAD_INV, 2 => PWM_3_GENA_ACTLOADR::PWM_3_GENA_ACTLOAD_ZERO, 3 => PWM_3_GENA_ACTLOADR::PWM_3_GENA_ACTLOAD_ONE, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTLOAD_NONE`"] #[inline(always)] pub fn is_pwm_3_gena_actload_none(&self) -> bool { *self == PWM_3_GENA_ACTLOADR::PWM_3_GENA_ACTLOAD_NONE } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTLOAD_INV`"] #[inline(always)] pub fn is_pwm_3_gena_actload_inv(&self) -> bool { *self == PWM_3_GENA_ACTLOADR::PWM_3_GENA_ACTLOAD_INV } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTLOAD_ZERO`"] #[inline(always)] pub fn is_pwm_3_gena_actload_zero(&self) -> bool { *self == PWM_3_GENA_ACTLOADR::PWM_3_GENA_ACTLOAD_ZERO } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTLOAD_ONE`"] #[inline(always)] pub fn is_pwm_3_gena_actload_one(&self) -> bool { *self == PWM_3_GENA_ACTLOADR::PWM_3_GENA_ACTLOAD_ONE } } #[doc = "Values that can be written to the field `PWM_3_GENA_ACTLOAD`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENA_ACTLOADW { #[doc = "Do nothing"] PWM_3_GENA_ACTLOAD_NONE, #[doc = "Invert pwmA"] PWM_3_GENA_ACTLOAD_INV, #[doc = "Drive pwmA Low"] PWM_3_GENA_ACTLOAD_ZERO, #[doc = "Drive pwmA High"] PWM_3_GENA_ACTLOAD_ONE, } impl PWM_3_GENA_ACTLOADW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { PWM_3_GENA_ACTLOADW::PWM_3_GENA_ACTLOAD_NONE => 0, PWM_3_GENA_ACTLOADW::PWM_3_GENA_ACTLOAD_INV => 1, PWM_3_GENA_ACTLOADW::PWM_3_GENA_ACTLOAD_ZERO => 2, PWM_3_GENA_ACTLOADW::PWM_3_GENA_ACTLOAD_ONE => 3, } } } #[doc = r"Proxy"] pub struct _PWM_3_GENA_ACTLOADW<'a> { w: &'a mut W, } impl<'a> _PWM_3_GENA_ACTLOADW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PWM_3_GENA_ACTLOADW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Do nothing"] #[inline(always)] pub fn pwm_3_gena_actload_none(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTLOADW::PWM_3_GENA_ACTLOAD_NONE) } #[doc = "Invert pwmA"] #[inline(always)] pub fn pwm_3_gena_actload_inv(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTLOADW::PWM_3_GENA_ACTLOAD_INV) } #[doc = "Drive pwmA Low"] #[inline(always)] pub fn pwm_3_gena_actload_zero(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTLOADW::PWM_3_GENA_ACTLOAD_ZERO) } #[doc = "Drive pwmA High"] #[inline(always)] pub fn pwm_3_gena_actload_one(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTLOADW::PWM_3_GENA_ACTLOAD_ONE) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 2); self.w.bits |= ((value as u32) & 3) << 2; self.w } } #[doc = "Possible values of the field `PWM_3_GENA_ACTCMPAU`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENA_ACTCMPAUR { #[doc = "Do nothing"] PWM_3_GENA_ACTCMPAU_NONE, #[doc = "Invert pwmA"] PWM_3_GENA_ACTCMPAU_INV, #[doc = "Drive pwmA Low"] PWM_3_GENA_ACTCMPAU_ZERO, #[doc = "Drive pwmA High"] PWM_3_GENA_ACTCMPAU_ONE, } impl PWM_3_GENA_ACTCMPAUR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { PWM_3_GENA_ACTCMPAUR::PWM_3_GENA_ACTCMPAU_NONE => 0, PWM_3_GENA_ACTCMPAUR::PWM_3_GENA_ACTCMPAU_INV => 1, PWM_3_GENA_ACTCMPAUR::PWM_3_GENA_ACTCMPAU_ZERO => 2, PWM_3_GENA_ACTCMPAUR::PWM_3_GENA_ACTCMPAU_ONE => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> PWM_3_GENA_ACTCMPAUR { match value { 0 => PWM_3_GENA_ACTCMPAUR::PWM_3_GENA_ACTCMPAU_NONE, 1 => PWM_3_GENA_ACTCMPAUR::PWM_3_GENA_ACTCMPAU_INV, 2 => PWM_3_GENA_ACTCMPAUR::PWM_3_GENA_ACTCMPAU_ZERO, 3 => PWM_3_GENA_ACTCMPAUR::PWM_3_GENA_ACTCMPAU_ONE, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTCMPAU_NONE`"] #[inline(always)] pub fn is_pwm_3_gena_actcmpau_none(&self) -> bool { *self == PWM_3_GENA_ACTCMPAUR::PWM_3_GENA_ACTCMPAU_NONE } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTCMPAU_INV`"] #[inline(always)] pub fn is_pwm_3_gena_actcmpau_inv(&self) -> bool { *self == PWM_3_GENA_ACTCMPAUR::PWM_3_GENA_ACTCMPAU_INV } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTCMPAU_ZERO`"] #[inline(always)] pub fn is_pwm_3_gena_actcmpau_zero(&self) -> bool { *self == PWM_3_GENA_ACTCMPAUR::PWM_3_GENA_ACTCMPAU_ZERO } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTCMPAU_ONE`"] #[inline(always)] pub fn is_pwm_3_gena_actcmpau_one(&self) -> bool { *self == PWM_3_GENA_ACTCMPAUR::PWM_3_GENA_ACTCMPAU_ONE } } #[doc = "Values that can be written to the field `PWM_3_GENA_ACTCMPAU`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENA_ACTCMPAUW { #[doc = "Do nothing"] PWM_3_GENA_ACTCMPAU_NONE, #[doc = "Invert pwmA"] PWM_3_GENA_ACTCMPAU_INV, #[doc = "Drive pwmA Low"] PWM_3_GENA_ACTCMPAU_ZERO, #[doc = "Drive pwmA High"] PWM_3_GENA_ACTCMPAU_ONE, } impl PWM_3_GENA_ACTCMPAUW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { PWM_3_GENA_ACTCMPAUW::PWM_3_GENA_ACTCMPAU_NONE => 0, PWM_3_GENA_ACTCMPAUW::PWM_3_GENA_ACTCMPAU_INV => 1, PWM_3_GENA_ACTCMPAUW::PWM_3_GENA_ACTCMPAU_ZERO => 2, PWM_3_GENA_ACTCMPAUW::PWM_3_GENA_ACTCMPAU_ONE => 3, } } } #[doc = r"Proxy"] pub struct _PWM_3_GENA_ACTCMPAUW<'a> { w: &'a mut W, } impl<'a> _PWM_3_GENA_ACTCMPAUW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PWM_3_GENA_ACTCMPAUW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Do nothing"] #[inline(always)] pub fn pwm_3_gena_actcmpau_none(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTCMPAUW::PWM_3_GENA_ACTCMPAU_NONE) } #[doc = "Invert pwmA"] #[inline(always)] pub fn pwm_3_gena_actcmpau_inv(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTCMPAUW::PWM_3_GENA_ACTCMPAU_INV) } #[doc = "Drive pwmA Low"] #[inline(always)] pub fn pwm_3_gena_actcmpau_zero(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTCMPAUW::PWM_3_GENA_ACTCMPAU_ZERO) } #[doc = "Drive pwmA High"] #[inline(always)] pub fn pwm_3_gena_actcmpau_one(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTCMPAUW::PWM_3_GENA_ACTCMPAU_ONE) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 4); self.w.bits |= ((value as u32) & 3) << 4; self.w } } #[doc = "Possible values of the field `PWM_3_GENA_ACTCMPAD`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENA_ACTCMPADR { #[doc = "Do nothing"] PWM_3_GENA_ACTCMPAD_NONE, #[doc = "Invert pwmA"] PWM_3_GENA_ACTCMPAD_INV, #[doc = "Drive pwmA Low"] PWM_3_GENA_ACTCMPAD_ZERO, #[doc = "Drive pwmA High"] PWM_3_GENA_ACTCMPAD_ONE, } impl PWM_3_GENA_ACTCMPADR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { PWM_3_GENA_ACTCMPADR::PWM_3_GENA_ACTCMPAD_NONE => 0, PWM_3_GENA_ACTCMPADR::PWM_3_GENA_ACTCMPAD_INV => 1, PWM_3_GENA_ACTCMPADR::PWM_3_GENA_ACTCMPAD_ZERO => 2, PWM_3_GENA_ACTCMPADR::PWM_3_GENA_ACTCMPAD_ONE => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> PWM_3_GENA_ACTCMPADR { match value { 0 => PWM_3_GENA_ACTCMPADR::PWM_3_GENA_ACTCMPAD_NONE, 1 => PWM_3_GENA_ACTCMPADR::PWM_3_GENA_ACTCMPAD_INV, 2 => PWM_3_GENA_ACTCMPADR::PWM_3_GENA_ACTCMPAD_ZERO, 3 => PWM_3_GENA_ACTCMPADR::PWM_3_GENA_ACTCMPAD_ONE, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTCMPAD_NONE`"] #[inline(always)] pub fn is_pwm_3_gena_actcmpad_none(&self) -> bool { *self == PWM_3_GENA_ACTCMPADR::PWM_3_GENA_ACTCMPAD_NONE } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTCMPAD_INV`"] #[inline(always)] pub fn is_pwm_3_gena_actcmpad_inv(&self) -> bool { *self == PWM_3_GENA_ACTCMPADR::PWM_3_GENA_ACTCMPAD_INV } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTCMPAD_ZERO`"] #[inline(always)] pub fn is_pwm_3_gena_actcmpad_zero(&self) -> bool { *self == PWM_3_GENA_ACTCMPADR::PWM_3_GENA_ACTCMPAD_ZERO } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTCMPAD_ONE`"] #[inline(always)] pub fn is_pwm_3_gena_actcmpad_one(&self) -> bool { *self == PWM_3_GENA_ACTCMPADR::PWM_3_GENA_ACTCMPAD_ONE } } #[doc = "Values that can be written to the field `PWM_3_GENA_ACTCMPAD`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENA_ACTCMPADW { #[doc = "Do nothing"] PWM_3_GENA_ACTCMPAD_NONE, #[doc = "Invert pwmA"] PWM_3_GENA_ACTCMPAD_INV, #[doc = "Drive pwmA Low"] PWM_3_GENA_ACTCMPAD_ZERO, #[doc = "Drive pwmA High"] PWM_3_GENA_ACTCMPAD_ONE, } impl PWM_3_GENA_ACTCMPADW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { PWM_3_GENA_ACTCMPADW::PWM_3_GENA_ACTCMPAD_NONE => 0, PWM_3_GENA_ACTCMPADW::PWM_3_GENA_ACTCMPAD_INV => 1, PWM_3_GENA_ACTCMPADW::PWM_3_GENA_ACTCMPAD_ZERO => 2, PWM_3_GENA_ACTCMPADW::PWM_3_GENA_ACTCMPAD_ONE => 3, } } } #[doc = r"Proxy"] pub struct _PWM_3_GENA_ACTCMPADW<'a> { w: &'a mut W, } impl<'a> _PWM_3_GENA_ACTCMPADW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PWM_3_GENA_ACTCMPADW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Do nothing"] #[inline(always)] pub fn pwm_3_gena_actcmpad_none(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTCMPADW::PWM_3_GENA_ACTCMPAD_NONE) } #[doc = "Invert pwmA"] #[inline(always)] pub fn pwm_3_gena_actcmpad_inv(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTCMPADW::PWM_3_GENA_ACTCMPAD_INV) } #[doc = "Drive pwmA Low"] #[inline(always)] pub fn pwm_3_gena_actcmpad_zero(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTCMPADW::PWM_3_GENA_ACTCMPAD_ZERO) } #[doc = "Drive pwmA High"] #[inline(always)] pub fn pwm_3_gena_actcmpad_one(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTCMPADW::PWM_3_GENA_ACTCMPAD_ONE) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 6); self.w.bits |= ((value as u32) & 3) << 6; self.w } } #[doc = "Possible values of the field `PWM_3_GENA_ACTCMPBU`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENA_ACTCMPBUR { #[doc = "Do nothing"] PWM_3_GENA_ACTCMPBU_NONE, #[doc = "Invert pwmA"] PWM_3_GENA_ACTCMPBU_INV, #[doc = "Drive pwmA Low"] PWM_3_GENA_ACTCMPBU_ZERO, #[doc = "Drive pwmA High"] PWM_3_GENA_ACTCMPBU_ONE, } impl PWM_3_GENA_ACTCMPBUR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { PWM_3_GENA_ACTCMPBUR::PWM_3_GENA_ACTCMPBU_NONE => 0, PWM_3_GENA_ACTCMPBUR::PWM_3_GENA_ACTCMPBU_INV => 1, PWM_3_GENA_ACTCMPBUR::PWM_3_GENA_ACTCMPBU_ZERO => 2, PWM_3_GENA_ACTCMPBUR::PWM_3_GENA_ACTCMPBU_ONE => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> PWM_3_GENA_ACTCMPBUR { match value { 0 => PWM_3_GENA_ACTCMPBUR::PWM_3_GENA_ACTCMPBU_NONE, 1 => PWM_3_GENA_ACTCMPBUR::PWM_3_GENA_ACTCMPBU_INV, 2 => PWM_3_GENA_ACTCMPBUR::PWM_3_GENA_ACTCMPBU_ZERO, 3 => PWM_3_GENA_ACTCMPBUR::PWM_3_GENA_ACTCMPBU_ONE, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTCMPBU_NONE`"] #[inline(always)] pub fn is_pwm_3_gena_actcmpbu_none(&self) -> bool { *self == PWM_3_GENA_ACTCMPBUR::PWM_3_GENA_ACTCMPBU_NONE } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTCMPBU_INV`"] #[inline(always)] pub fn is_pwm_3_gena_actcmpbu_inv(&self) -> bool { *self == PWM_3_GENA_ACTCMPBUR::PWM_3_GENA_ACTCMPBU_INV } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTCMPBU_ZERO`"] #[inline(always)] pub fn is_pwm_3_gena_actcmpbu_zero(&self) -> bool { *self == PWM_3_GENA_ACTCMPBUR::PWM_3_GENA_ACTCMPBU_ZERO } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTCMPBU_ONE`"] #[inline(always)] pub fn is_pwm_3_gena_actcmpbu_one(&self) -> bool { *self == PWM_3_GENA_ACTCMPBUR::PWM_3_GENA_ACTCMPBU_ONE } } #[doc = "Values that can be written to the field `PWM_3_GENA_ACTCMPBU`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENA_ACTCMPBUW { #[doc = "Do nothing"] PWM_3_GENA_ACTCMPBU_NONE, #[doc = "Invert pwmA"] PWM_3_GENA_ACTCMPBU_INV, #[doc = "Drive pwmA Low"] PWM_3_GENA_ACTCMPBU_ZERO, #[doc = "Drive pwmA High"] PWM_3_GENA_ACTCMPBU_ONE, } impl PWM_3_GENA_ACTCMPBUW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { PWM_3_GENA_ACTCMPBUW::PWM_3_GENA_ACTCMPBU_NONE => 0, PWM_3_GENA_ACTCMPBUW::PWM_3_GENA_ACTCMPBU_INV => 1, PWM_3_GENA_ACTCMPBUW::PWM_3_GENA_ACTCMPBU_ZERO => 2, PWM_3_GENA_ACTCMPBUW::PWM_3_GENA_ACTCMPBU_ONE => 3, } } } #[doc = r"Proxy"] pub struct _PWM_3_GENA_ACTCMPBUW<'a> { w: &'a mut W, } impl<'a> _PWM_3_GENA_ACTCMPBUW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PWM_3_GENA_ACTCMPBUW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Do nothing"] #[inline(always)] pub fn pwm_3_gena_actcmpbu_none(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTCMPBUW::PWM_3_GENA_ACTCMPBU_NONE) } #[doc = "Invert pwmA"] #[inline(always)] pub fn pwm_3_gena_actcmpbu_inv(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTCMPBUW::PWM_3_GENA_ACTCMPBU_INV) } #[doc = "Drive pwmA Low"] #[inline(always)] pub fn pwm_3_gena_actcmpbu_zero(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTCMPBUW::PWM_3_GENA_ACTCMPBU_ZERO) } #[doc = "Drive pwmA High"] #[inline(always)] pub fn pwm_3_gena_actcmpbu_one(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTCMPBUW::PWM_3_GENA_ACTCMPBU_ONE) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 8); self.w.bits |= ((value as u32) & 3) << 8; self.w } } #[doc = "Possible values of the field `PWM_3_GENA_ACTCMPBD`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENA_ACTCMPBDR { #[doc = "Do nothing"] PWM_3_GENA_ACTCMPBD_NONE, #[doc = "Invert pwmA"] PWM_3_GENA_ACTCMPBD_INV, #[doc = "Drive pwmA Low"] PWM_3_GENA_ACTCMPBD_ZERO, #[doc = "Drive pwmA High"] PWM_3_GENA_ACTCMPBD_ONE, } impl PWM_3_GENA_ACTCMPBDR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { PWM_3_GENA_ACTCMPBDR::PWM_3_GENA_ACTCMPBD_NONE => 0, PWM_3_GENA_ACTCMPBDR::PWM_3_GENA_ACTCMPBD_INV => 1, PWM_3_GENA_ACTCMPBDR::PWM_3_GENA_ACTCMPBD_ZERO => 2, PWM_3_GENA_ACTCMPBDR::PWM_3_GENA_ACTCMPBD_ONE => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> PWM_3_GENA_ACTCMPBDR { match value { 0 => PWM_3_GENA_ACTCMPBDR::PWM_3_GENA_ACTCMPBD_NONE, 1 => PWM_3_GENA_ACTCMPBDR::PWM_3_GENA_ACTCMPBD_INV, 2 => PWM_3_GENA_ACTCMPBDR::PWM_3_GENA_ACTCMPBD_ZERO, 3 => PWM_3_GENA_ACTCMPBDR::PWM_3_GENA_ACTCMPBD_ONE, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTCMPBD_NONE`"] #[inline(always)] pub fn is_pwm_3_gena_actcmpbd_none(&self) -> bool { *self == PWM_3_GENA_ACTCMPBDR::PWM_3_GENA_ACTCMPBD_NONE } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTCMPBD_INV`"] #[inline(always)] pub fn is_pwm_3_gena_actcmpbd_inv(&self) -> bool { *self == PWM_3_GENA_ACTCMPBDR::PWM_3_GENA_ACTCMPBD_INV } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTCMPBD_ZERO`"] #[inline(always)] pub fn is_pwm_3_gena_actcmpbd_zero(&self) -> bool { *self == PWM_3_GENA_ACTCMPBDR::PWM_3_GENA_ACTCMPBD_ZERO } #[doc = "Checks if the value of the field is `PWM_3_GENA_ACTCMPBD_ONE`"] #[inline(always)] pub fn is_pwm_3_gena_actcmpbd_one(&self) -> bool { *self == PWM_3_GENA_ACTCMPBDR::PWM_3_GENA_ACTCMPBD_ONE } } #[doc = "Values that can be written to the field `PWM_3_GENA_ACTCMPBD`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PWM_3_GENA_ACTCMPBDW { #[doc = "Do nothing"] PWM_3_GENA_ACTCMPBD_NONE, #[doc = "Invert pwmA"] PWM_3_GENA_ACTCMPBD_INV, #[doc = "Drive pwmA Low"] PWM_3_GENA_ACTCMPBD_ZERO, #[doc = "Drive pwmA High"] PWM_3_GENA_ACTCMPBD_ONE, } impl PWM_3_GENA_ACTCMPBDW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { PWM_3_GENA_ACTCMPBDW::PWM_3_GENA_ACTCMPBD_NONE => 0, PWM_3_GENA_ACTCMPBDW::PWM_3_GENA_ACTCMPBD_INV => 1, PWM_3_GENA_ACTCMPBDW::PWM_3_GENA_ACTCMPBD_ZERO => 2, PWM_3_GENA_ACTCMPBDW::PWM_3_GENA_ACTCMPBD_ONE => 3, } } } #[doc = r"Proxy"] pub struct _PWM_3_GENA_ACTCMPBDW<'a> { w: &'a mut W, } impl<'a> _PWM_3_GENA_ACTCMPBDW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PWM_3_GENA_ACTCMPBDW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Do nothing"] #[inline(always)] pub fn pwm_3_gena_actcmpbd_none(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTCMPBDW::PWM_3_GENA_ACTCMPBD_NONE) } #[doc = "Invert pwmA"] #[inline(always)] pub fn pwm_3_gena_actcmpbd_inv(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTCMPBDW::PWM_3_GENA_ACTCMPBD_INV) } #[doc = "Drive pwmA Low"] #[inline(always)] pub fn pwm_3_gena_actcmpbd_zero(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTCMPBDW::PWM_3_GENA_ACTCMPBD_ZERO) } #[doc = "Drive pwmA High"] #[inline(always)] pub fn pwm_3_gena_actcmpbd_one(self) -> &'a mut W { self.variant(PWM_3_GENA_ACTCMPBDW::PWM_3_GENA_ACTCMPBD_ONE) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(3 << 10); self.w.bits |= ((value as u32) & 3) << 10; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:1 - Action for Counter=0"] #[inline(always)] pub fn pwm_3_gena_actzero(&self) -> PWM_3_GENA_ACTZEROR { PWM_3_GENA_ACTZEROR::_from(((self.bits >> 0) & 3) as u8) } #[doc = "Bits 2:3 - Action for Counter=LOAD"] #[inline(always)] pub fn pwm_3_gena_actload(&self) -> PWM_3_GENA_ACTLOADR { PWM_3_GENA_ACTLOADR::_from(((self.bits >> 2) & 3) as u8) } #[doc = "Bits 4:5 - Action for Comparator A Up"] #[inline(always)] pub fn pwm_3_gena_actcmpau(&self) -> PWM_3_GENA_ACTCMPAUR { PWM_3_GENA_ACTCMPAUR::_from(((self.bits >> 4) & 3) as u8) } #[doc = "Bits 6:7 - Action for Comparator A Down"] #[inline(always)] pub fn pwm_3_gena_actcmpad(&self) -> PWM_3_GENA_ACTCMPADR { PWM_3_GENA_ACTCMPADR::_from(((self.bits >> 6) & 3) as u8) } #[doc = "Bits 8:9 - Action for Comparator B Up"] #[inline(always)] pub fn pwm_3_gena_actcmpbu(&self) -> PWM_3_GENA_ACTCMPBUR { PWM_3_GENA_ACTCMPBUR::_from(((self.bits >> 8) & 3) as u8) } #[doc = "Bits 10:11 - Action for Comparator B Down"] #[inline(always)] pub fn pwm_3_gena_actcmpbd(&self) -> PWM_3_GENA_ACTCMPBDR { PWM_3_GENA_ACTCMPBDR::_from(((self.bits >> 10) & 3) as u8) } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:1 - Action for Counter=0"] #[inline(always)] pub fn pwm_3_gena_actzero(&mut self) -> _PWM_3_GENA_ACTZEROW { _PWM_3_GENA_ACTZEROW { w: self } } #[doc = "Bits 2:3 - Action for Counter=LOAD"] #[inline(always)] pub fn pwm_3_gena_actload(&mut self) -> _PWM_3_GENA_ACTLOADW { _PWM_3_GENA_ACTLOADW { w: self } } #[doc = "Bits 4:5 - Action for Comparator A Up"] #[inline(always)] pub fn pwm_3_gena_actcmpau(&mut self) -> _PWM_3_GENA_ACTCMPAUW { _PWM_3_GENA_ACTCMPAUW { w: self } } #[doc = "Bits 6:7 - Action for Comparator A Down"] #[inline(always)] pub fn pwm_3_gena_actcmpad(&mut self) -> _PWM_3_GENA_ACTCMPADW { _PWM_3_GENA_ACTCMPADW { w: self } } #[doc = "Bits 8:9 - Action for Comparator B Up"] #[inline(always)] pub fn pwm_3_gena_actcmpbu(&mut self) -> _PWM_3_GENA_ACTCMPBUW { _PWM_3_GENA_ACTCMPBUW { w: self } } #[doc = "Bits 10:11 - Action for Comparator B Down"] #[inline(always)] pub fn pwm_3_gena_actcmpbd(&mut self) -> _PWM_3_GENA_ACTCMPBDW { _PWM_3_GENA_ACTCMPBDW { w: self } } }
// Copyright 2018 The Rio Advancement Inc // //! A module containing the middleware of the HTTP server use std::str; use rand::{self, Rng}; use error::{Result, Error}; use handlebars::Handlebars; use failure::SyncFailure; use config; use lib_load; /// path where the .so file stored const ROOT_PATH: &'static str = "../../tools/license/"; const NALPERION_SHAFER_FILECHK_XML_TEMPLATE: &'static str = include_str!("../tools/shafer_filechk.xml"); /// These are the security values stamped into your library. /// They should be changed to match your vaues. const AUTH_1: u32 = 6; const AUTH_2: u32 = 502; const AUTH_3: u32 = 234; /// These values should be set to your customer ID and /// product ID. They are used to verify that the library /// being accessed corresponds to your product. const CUSTOMER_ID: u32 = 4979; const PRODUCT_ID: u32 = 0100; const NALP_LIB_OPEN: &'static str = "NalpLibOpen"; const NALP_VALIDATE_LIBRARY: &'static str = "NSLValidateLibrary"; const NALP_CLOSED_LIBRARY: &'static str = "NalpLibClose"; const NALP_GET_LIBRARY: &'static str = "NSLGetLicense"; #[derive(Debug)] pub struct Nalperion { fascade: API, } impl Nalperion { pub fn new(config: config::LicensesCfg) -> Self { Nalperion { fascade: API::new( config.so_file.to_string(), config.activation_code, ), } } // Returns the status of license verified with nalperion pub fn verify(&self) -> Result<()> { self.fascade.check_license()?; Ok(()) } } #[derive(Debug)] struct API { so_file: String, activation_code: Option<String>, secret_value: u32, } impl API { fn new(so_file: String, activation_code: Option<String>) -> Self { API { so_file: so_file, activation_code: activation_code, secret_value: rand::thread_rng().gen_range(0, 500), } } fn secret_offset(&self) -> (u32, u32) { ( AUTH_1 + ((self.secret_value * AUTH_2) % AUTH_3), self.secret_value, ) } fn check_license(&self) -> Result<()> { Self::call_dynamic(self.so_file.clone(), self.secret_offset(),self.activation_code.clone())?; Ok(()) } fn call_dynamic(so_file: String, secret_offset: (u32, u32),activation_code:Option<String>) -> Result<()> { let lib = lib_load::Library::new(ROOT_PATH.to_string() + &so_file)?; unsafe { // open the nsl library and initialize the lib let open_fn = lib.get::<fn(&[u8]) -> i32>(NALP_LIB_OPEN.as_bytes())?; let ret_val = open_fn(shaferchk_xml_as_bytes(secret_offset.1)?.as_bytes()); if ret_val < 0 { return NalperionResult::from_err(NALP_LIB_OPEN); } //validate the library with customer id and product id let validate_fn = lib.get::<fn(u32, u32) -> i32>( NALP_VALIDATE_LIBRARY.as_bytes(), )?; let response = validate_fn(CUSTOMER_ID, PRODUCT_ID); if response - secret_offset.0 as i32 != 0 { return NalperionResult::from_err(NALP_VALIDATE_LIBRARY); } //check the status of the license (license status has negative value return the error) let get_license_fn = lib.get::<fn(Option<String>, *mut i32, Option<String>) -> i32>( NALP_GET_LIBRARY.as_bytes(), )?; let x: &mut i32 = &mut 0; let ret_val = get_license_fn(activation_code, x, None); if ret_val - secret_offset.0 as i32 != 0 { return NalperionResult::from_err(NALP_GET_LIBRARY); } if *x < 0 { return NalperionResult::from_value(*x); } // lib must be close (if not close `core dump` error occurs) let free_fn = lib.get::<fn() -> i32>(NALP_CLOSED_LIBRARY.as_bytes())?; let ret_val = free_fn(); if ret_val < 0 { return NalperionResult::from_err(NALP_CLOSED_LIBRARY); } Ok(()) } } } fn shaferchk_xml_as_bytes(secret_value: u32) -> Result<String> { let json = json!({ "secVal": secret_value, "WorkDir": ROOT_PATH }); let r = Handlebars::new() .render_template(NALPERION_SHAFER_FILECHK_XML_TEMPLATE, &json) .map_err(SyncFailure::new); let write_content = r.unwrap() .lines() .filter(|l| *l != "") .collect::<Vec<_>>() .join("\n") + "\n"; Ok(write_content.to_string()) } enum NalperionResult {} impl NalperionResult { pub fn from_value(v: i32) -> Result<()> { match v { // Error can Generated based on nalperion error code refer link: https://naldoc.atlassian.net/wiki/spaces/NND/pages/426049/Developers+API+Latest -1 => Err(Error::ProductExpired), -113 => Err(Error::TrialExpired), -116 => Err(Error::SubscriptionExpired), _ => Ok(()), } } pub fn from_err(name: &str) -> Result<()> { match name { NALP_LIB_OPEN => Err(Error::LicenseAPINotFound), NALP_VALIDATE_LIBRARY => Err(Error::LicenseAPIMustBeValid), NALP_GET_LIBRARY => Err(Error::LicenseCodeMustBeValid), NALP_CLOSED_LIBRARY => Err(Error::LicenseAPIMustBeInConsistentState), _ => Ok(()), } } }
fn no_large_group(pw: &[u8]) -> bool { let mut last = pw[0]; let mut last_count = 1; for &p in &pw[1..] { if p == last { last_count += 1; } else { if last_count == 2 { return true; } last = p; last_count = 1; } } last_count == 2 } fn main() { let two_same = |pw: &[u8]| pw.windows(2).any(|w| w[0] == w[1]); let never_dec = |pw: &[u8]| pw.windows(2).all(|w| w[0] <= w[1]); let part1 = (138241..=674034).map(|n| n.to_string()).filter(|pw| two_same(pw.as_bytes()) && never_dec(pw.as_bytes())).count(); let part2 = (138241..=674034).map(|n| n.to_string()).filter(|pw| two_same(pw.as_bytes()) && never_dec(pw.as_bytes()) && no_large_group(pw.as_bytes())).count(); println!("Part 2: {}", part1); println!("Part 2: {}", part2); }
#[path = "insert_before_3/with_nil_reference_child_appends_new_child.rs"] pub mod with_nil_reference_child_appends_new_child; #[path = "insert_before_3/with_reference_child_inserts_before_reference_child.rs"] pub mod with_reference_child_inserts_before_reference_child; use super::*; use wasm_bindgen::JsCast; use js_sys::{Reflect, Symbol}; use web_sys::Element; #[wasm_bindgen_test] async fn with_nil_reference_child_appends_new_child() { start_once(); let promise = r#async::apply_3::promise( module(), with_nil_reference_child_appends_new_child::function(), vec![], Default::default(), ) .unwrap(); let resolved = JsFuture::from(promise).await.unwrap(); assert!( js_sys::Array::is_array(&resolved), "{:?} is not an array", resolved ); let resolved_array: js_sys::Array = resolved.dyn_into().unwrap(); assert_eq!(resolved_array.length(), 2); let ok: JsValue = Symbol::for_("ok").into(); assert_eq!(Reflect::get(&resolved_array, &0.into()).unwrap(), ok); let inserted_child = Reflect::get(&resolved_array, &1.into()).unwrap(); assert!(inserted_child.has_type::<Element>()); let inserted_element: Element = inserted_child.dyn_into().unwrap(); assert_eq!(inserted_element.tag_name(), "ul"); let previous_element_sibling = inserted_element.previous_element_sibling().unwrap(); assert_eq!(previous_element_sibling.tag_name(), "table"); } #[wasm_bindgen_test] async fn with_reference_child_inserts_before_reference_child() { start_once(); let promise = r#async::apply_3::promise( module(), with_reference_child_inserts_before_reference_child::function(), vec![], Default::default(), ) .unwrap(); let resolved = JsFuture::from(promise).await.unwrap(); assert!( js_sys::Array::is_array(&resolved), "{:?} is not an array", resolved ); let resolved_array: js_sys::Array = resolved.dyn_into().unwrap(); assert_eq!(resolved_array.length(), 2); let ok: JsValue = Symbol::for_("ok").into(); assert_eq!(Reflect::get(&resolved_array, &0.into()).unwrap(), ok); let inserted_child = Reflect::get(&resolved_array, &1.into()).unwrap(); assert!(inserted_child.has_type::<Element>()); let inserted_element: Element = inserted_child.dyn_into().unwrap(); assert_eq!(inserted_element.tag_name(), "ul"); let next_element_sibling = inserted_element.next_element_sibling().unwrap(); assert_eq!(next_element_sibling.tag_name(), "table"); } fn module() -> Atom { Atom::from_str("Elixir.Lumen.Web.Node.InsertBefore3") }
//required in order for near_bindgen macro to work outside of lib.rs use crate::domain::RegisteredAccount; use crate::errors::account_management::ACCOUNT_NOT_REGISTERED; use crate::*; use crate::{ core::Hash, domain::{Account, YoctoNear}, errors::account_management::{ ACCOUNT_ALREADY_REGISTERED, INSUFFICIENT_STORAGE_FEE, UNREGISTER_REQUIRES_ZERO_BALANCES, }, interface::{self, AccountManagement, StakeAccount, StakingService}, }; use near_sdk::{ env, json_types::{ValidAccountId, U128}, near_bindgen, Promise, }; #[near_bindgen] impl AccountManagement for Contract { /// ## Logic /// - check attached deposit /// - assert amount is enough to cover storage fees /// - track the account storage fees /// - refunds funds minus account storage fees /// /// ## Panics /// - if attached deposit is not enough to cover account storage fees /// - if account is already registered #[payable] fn register_account(&mut self) { assert!( env::attached_deposit() >= self.account_storage_fee().value(), INSUFFICIENT_STORAGE_FEE, ); let account_storage_fee = self.account_storage_fee().into(); self.total_account_storage_escrow += account_storage_fee; let account = Account::new(account_storage_fee); assert!( self.save_account(&Hash::from(&env::predecessor_account_id()), &account), ACCOUNT_ALREADY_REGISTERED ); // refund over payment of storage fees let refund = env::attached_deposit() - account_storage_fee.value(); if refund > 0 { Promise::new(env::predecessor_account_id()).transfer(refund); } } fn unregister_account(&mut self) { let account_id = env::predecessor_account_id(); let account_id_hash = Hash::from(&env::predecessor_account_id()); match self.delete_account(&account_id_hash) { None => panic!(ACCOUNT_NOT_REGISTERED), Some(account) => { assert!(!account.has_funds(), UNREGISTER_REQUIRES_ZERO_BALANCES); self.total_account_storage_escrow -= account.storage_escrow.amount(); // refund the escrowed storage fee Promise::new(account_id).transfer(account.storage_escrow.amount().value()); } }; } /// returns the required account storage fee that needs to be attached to the account registration /// contract function call in yoctoNEAR /// /// NOTE: this is dynamic based on the storage cost per byte specified in the config fn account_storage_fee(&self) -> interface::YoctoNear { let fee = self.config.storage_cost_per_byte().value() * self.account_storage_usage.value() as u128; fee.into() } fn account_registered(&self, account_id: ValidAccountId) -> bool { self.accounts.contains_key(&Hash::from(account_id)) } fn total_registered_accounts(&self) -> U128 { self.accounts_len.into() } fn lookup_account(&self, account_id: ValidAccountId) -> Option<StakeAccount> { self.accounts .get(&Hash::from(account_id)) .map(|account| self.apply_receipt_funds_for_view(&account)) .map(|account| { let redeem_stake_batch = account.redeem_stake_batch.map(|batch| { interface::RedeemStakeBatch::from( batch, self.redeem_stake_batch_receipt(batch.id().into()), ) }); let next_redeem_stake_batch = account.next_redeem_stake_batch.map(|batch| { interface::RedeemStakeBatch::from( batch, self.redeem_stake_batch_receipt(batch.id().into()), ) }); let contract_near_liquidity = if self.near_liquidity_pool.value() == 0 { None } else { let mut total_unstaked_near = YoctoNear(0); let mut update_total_unstaked_near = |batch: &interface::RedeemStakeBatch| { if let Some(receipt) = batch.receipt.as_ref() { let stake_token_value: domain::StakeTokenValue = receipt.stake_token_value.clone().into(); total_unstaked_near += stake_token_value.stake_to_near(receipt.redeemed_stake.0 .0.into()); } }; if let Some(batch) = redeem_stake_batch.as_ref() { update_total_unstaked_near(batch); } if let Some(batch) = next_redeem_stake_batch.as_ref() { update_total_unstaked_near(batch); } if total_unstaked_near.value() > 0 { if self.near_liquidity_pool.value() >= total_unstaked_near.value() { Some(total_unstaked_near.into()) } else { Some(self.near_liquidity_pool.into()) } } else { None } }; StakeAccount { storage_escrow: account.storage_escrow.into(), near: account.near.map(Into::into), stake: account.stake.map(Into::into), stake_batch: account.stake_batch.map(Into::into), next_stake_batch: account.next_stake_batch.map(Into::into), redeem_stake_batch, next_redeem_stake_batch, contract_near_liquidity, } }) } } impl Contract { /// ## Panics /// if account is not registered pub(crate) fn registered_account(&self, account_id: &str) -> RegisteredAccount { let account_id_hash = Hash::from(account_id); match self.accounts.get(&Hash::from(account_id)) { Some(account) => RegisteredAccount { account, id: account_id_hash, }, None => panic!("{}: {}", ACCOUNT_NOT_REGISTERED, account_id), } } pub(crate) fn lookup_registered_account(&self, account_id: &str) -> Option<RegisteredAccount> { let account_id_hash = Hash::from(account_id); self.accounts .get(&Hash::from(account_id)) .map(|account| RegisteredAccount { account, id: account_id_hash, }) } pub(crate) fn predecessor_registered_account(&self) -> RegisteredAccount { self.registered_account(&env::predecessor_account_id()) } /// returns true if this was a new account fn save_account(&mut self, account_id: &Hash, account: &Account) -> bool { if self.accounts.insert(account_id, account).is_none() { // new account was added self.accounts_len += 1; return true; } false } pub(crate) fn save_registered_account(&mut self, account: &RegisteredAccount) { self.save_account(&account.id, &account.account); } /// returns the account that was deleted, or None if no account exists for specified account ID fn delete_account(&mut self, account_id: &Hash) -> Option<Account> { self.accounts.remove(account_id).map(|account| { self.accounts_len -= 1; account }) } } #[cfg(test)] mod test_register_account { use super::*; use crate::interface::AccountManagement; use crate::near::YOCTO; use crate::test_utils::*; use near_sdk::test_utils::get_created_receipts; use near_sdk::{testing_env, MockedBlockchain}; use std::convert::TryInto; /// When a user registers a new account /// And attaches more then the required payment for account storage /// Then the difference will be refunded #[test] fn register_new_account_with_deposit_overpayment() { let mut test_context = TestContext::new(); let mut context = test_context.context.clone(); let contract = &mut test_context.contract; let account_id = test_context.account_id; // Given the account is not currently registered assert!( !contract.account_registered(account_id.try_into().unwrap()), "account should not be registered" ); // measure how much actual storage is consumed by the new account let storage_before_registering_account = env::storage_usage(); // desposit is required for registering the account - 1 NEAR is more than enough // the account will be refunded the difference context.attached_deposit = YOCTO; testing_env!(context.clone()); contract.register_account(); // the txn should have created a Transfer receipt to refund the storage fee over payment let receipts = deserialize_receipts(); assert_eq!(receipts.len(), 1); let receipt = &receipts[0]; match receipt.actions.first().unwrap() { Action::Transfer { deposit } => assert_eq!( *deposit, context.attached_deposit - contract.account_storage_fee().value() ), action => panic!("unexpected action: {:?}", action), }; let account = contract.registered_account(account_id); assert_eq!( contract.total_registered_accounts().0, 1, "There should be 1 account registered" ); let account_storage_usage = env::storage_usage() - storage_before_registering_account; assert_eq!( account_storage_usage, 119, "account storage usage changed !!! If the change is expected, then update the assert" ); // And the storage fee credit is applied on the account assert_eq!( account.storage_escrow.amount(), contract.account_storage_fee().into() ); assert_eq!( contract.total_account_storage_escrow, account.storage_escrow.amount() ) } #[test] fn register_account_with_exact_storage_fee() { let mut test_context = TestContext::new(); let mut context = test_context.context.clone(); let contract = &mut test_context.contract; context.attached_deposit = contract.account_storage_fee().value(); testing_env!(context.clone()); contract.register_account(); // no refund is expected assert!(get_created_receipts().is_empty()); } #[test] #[should_panic(expected = "account is already registered")] fn register_preexisting_account() { let mut test_context = TestContext::with_registered_account(); let mut context = test_context.context.clone(); context.attached_deposit = YOCTO; testing_env!(context); test_context.contract.register_account(); } #[test] #[should_panic(expected = "sufficient deposit is required to pay for account storage fees")] fn register_account_with_no_attached_deposit() { let mut test_context = TestContext::new(); test_context.contract.register_account(); } #[test] #[should_panic(expected = "sufficient deposit is required to pay for account storage fees")] fn register_account_with_insufficient_deposit_for_storage_fees() { let mut test_context = TestContext::new(); test_context.context.attached_deposit = 1; testing_env!(test_context.context.clone()); test_context.contract.register_account(); } } #[cfg(test)] mod test_unregister_account { use super::*; use crate::interface::AccountManagement; use crate::near::YOCTO; use crate::test_utils::*; use near_sdk::{testing_env, MockedBlockchain}; use std::convert::TryInto; use std::ops::DerefMut; #[test] fn unregister_registered_account_with_no_funds() { let test_context = TestContext::with_registered_account(); let mut contract = test_context.contract; assert_eq!( contract.total_account_storage_escrow, contract.account_storage_fee().into() ); contract.unregister_account(); assert!(!contract.account_registered(test_context.account_id.try_into().unwrap())); let receipts = deserialize_receipts(); // account storage fee should have been refunded assert_eq!(receipts.len(), 1); let receipt = &receipts[0]; assert_eq!(&receipt.receiver_id, test_context.account_id); match &receipt.actions[0] { Action::Transfer { deposit } => { assert_eq!(*deposit, contract.account_storage_fee().value()) } _ => panic!("expected account storage fee to be refunded"), } assert_eq!(contract.total_account_storage_escrow, 0.into()); } #[test] #[should_panic( expected = "all funds must be withdrawn from the account in order to unregister" )] fn unregister_account_with_stake_funds() { let mut test_context = TestContext::with_registered_account(); let contract = &mut test_context.contract; // apply STAKE credit to the account let mut registered_account = contract.registered_account(test_context.account_id); registered_account.account.apply_stake_credit(1.into()); contract.save_registered_account(&registered_account); // then unregister will fail contract.unregister_account(); } #[test] #[should_panic( expected = "all funds must be withdrawn from the account in order to unregister" )] fn unregister_account_with_near_funds() { let mut test_context = TestContext::with_registered_account(); let contract = &mut test_context.contract; // credit some NEAR let mut account = contract.registered_account(test_context.account_id); account.deref_mut().apply_near_credit(1.into()); contract.save_registered_account(&account); // unregister should fail contract.unregister_account(); } #[test] #[should_panic( expected = "all funds must be withdrawn from the account in order to unregister" )] fn account_has_funds_in_stake_batch() { let mut test_context = TestContext::with_registered_account(); let mut context = test_context.context; let contract = &mut test_context.contract; // credit some NEAR context.attached_deposit = YOCTO; testing_env!(context.clone()); contract.deposit(); // unregister should fail contract.unregister_account(); } #[test] #[should_panic( expected = "all funds must be withdrawn from the account in order to unregister" )] fn account_has_funds_in_next_stake_batch() { let mut test_context = TestContext::with_registered_account(); let mut context = test_context.context; let contract = &mut test_context.contract; // credit some NEAR context.attached_deposit = YOCTO; testing_env!(context.clone()); // setting the lock to true should cause the deposit to be put in the next stake batch contract.stake_batch_lock = Some(StakeLock::Staking); contract.deposit(); // confirm that account has funds in next stake batch let registered_account = contract.registered_account(test_context.account_id); assert!(registered_account.account.next_stake_batch.is_some()); // unregister should fail contract.unregister_account(); } #[test] #[should_panic( expected = "all funds must be withdrawn from the account in order to unregister" )] fn account_has_funds_in_redeem_stake_batch() { let mut test_context = TestContext::with_registered_account(); let contract = &mut test_context.contract; // give the account STAKE let mut registered_account = contract.registered_account(test_context.account_id); registered_account.apply_stake_credit(YOCTO.into()); contract.save_registered_account(&registered_account); // then redeem it to move the STAKE funds in the redeem stake batch contract.redeem_all(); // unregister should fail contract.unregister_account(); } #[test] #[should_panic( expected = "all funds must be withdrawn from the account in order to unregister" )] fn account_has_funds_in_next_redeem_stake_batch() { let mut test_context = TestContext::with_registered_account(); let contract = &mut test_context.contract; // give the account STAKE let mut registered_account = contract.registered_account(test_context.account_id); registered_account.apply_stake_credit(YOCTO.into()); contract.save_registered_account(&registered_account); // set lock to pending withdrawal to force STAKE funds to go into the next redeem batch contract.redeem_stake_batch_lock = Some(RedeemLock::PendingWithdrawal); // pending withdrawal requires redeem stake batch to be present contract.redeem_stake_batch = Some(RedeemStakeBatch::new( contract.batch_id_sequence, YOCTO.into(), )); // then redeem it to move the STAKE funds in the redeem stake batch contract.redeem_all(); // confirm there is a next redeem stake batch let registered_account = contract.registered_account(test_context.account_id); assert!(registered_account.account.next_redeem_stake_batch.is_some()); // unregister should fail contract.unregister_account(); } #[test] #[should_panic(expected = "account is not registered")] fn unregister_unknown_account() { let mut test_context = TestContext::new(); test_context.contract.unregister_account(); } } #[cfg(test)] mod test_lookup_account { use super::*; use crate::interface::{AccountManagement, StakingService}; use crate::near::YOCTO; use crate::test_utils::*; use near_sdk::{testing_env, MockedBlockchain}; use std::convert::TryInto; #[test] fn lookup_registered_account() { let test_context = TestContext::with_registered_account(); test_context .contract .lookup_account(test_context.account_id.try_into().unwrap()) .expect("account should be registered"); } #[test] fn lookup_unregistered_account() { let test_context = TestContext::new(); assert!(test_context .contract .lookup_account(test_context.account_id.try_into().unwrap()) .is_none()); } /// when an account has unclaimed receipts, the receipts are applied to the account balances /// for display purposes - so as not to confuse the end user #[test] fn with_unclaimed_receipts() { let mut ctx = TestContext::with_registered_account(); let mut context = ctx.context; let contract = &mut ctx.contract; // setup receipts for the account { // deposit funds into a stake batch context.attached_deposit = 10_u128 * YOCTO; testing_env!(context.clone()); contract.deposit(); // simulate that the batch was processed and create a batch receipt for it let batch = contract.stake_batch.unwrap(); // create a stake batch receipt for the stake batch let receipt = domain::StakeBatchReceipt::new( batch.balance().amount(), contract.stake_token_value, ); contract.stake_batch_receipts.insert(&batch.id(), &receipt); contract.stake_batch = None; // credit the account with some STAKE and then redeem it let mut registered_account = contract.registered_account(ctx.account_id); registered_account .account .apply_stake_credit((YOCTO * 2).into()); contract.save_registered_account(&registered_account); contract.redeem((YOCTO * 2).into()); // create a receipt for the batch let redeem_stake_batch_receipt = contract .redeem_stake_batch .unwrap() .create_receipt(contract.stake_token_value); contract .redeem_stake_batch_receipts .insert(&contract.batch_id_sequence, &redeem_stake_batch_receipt); } context.is_view = true; testing_env!(context.clone()); let account = contract .lookup_account(ctx.account_id.try_into().unwrap()) .unwrap(); assert!(account.stake_batch.is_none()); assert!(account.redeem_stake_batch.is_none()); assert_eq!(account.stake.unwrap().amount, (10_u128 * YOCTO).into()); assert_eq!(account.near.unwrap().amount, (2_u128 * YOCTO).into()); } #[test] fn with_unclaimed_receipts_pending_withdrawal() { let mut ctx = TestContext::with_registered_account(); let mut context = ctx.context; let contract = &mut ctx.contract; // setup { // credit the account some STAKE and then redeem it all let mut registered_account = contract.registered_account(ctx.account_id); registered_account .account .apply_stake_credit((YOCTO * 10).into()); contract.save_registered_account(&registered_account); contract.redeem_all(); let batch = contract.redeem_stake_batch.unwrap(); let receipt = batch.create_receipt(contract.stake_token_value); contract .redeem_stake_batch_receipts .insert(&batch.id(), &receipt); contract.redeem_stake_batch_lock = Some(RedeemLock::PendingWithdrawal); } context.is_view = true; testing_env!(context.clone()); let account = contract .lookup_account(ctx.account_id.try_into().unwrap()) .unwrap(); assert!(account.stake_batch.is_none()); assert!(account.stake.is_none()); assert!(account.near.is_none()); account .redeem_stake_batch .unwrap() .receipt .expect("receipt for pending withdrawal should be present"); } } #[cfg(test)] mod test { use super::*; use crate::interface::AccountManagement; use crate::test_utils::*; use near_sdk::{testing_env, MockedBlockchain}; use std::convert::TryFrom; /// the following contract funcs are expected to be invoked in view mode: /// - account_storage_fee /// - account_registered /// - total_registered_accounts /// - lookup_account #[test] fn check_view_funcs() { let mut ctx = TestContext::new(); // given the funcs are called in view mode ctx.context.is_view = true; testing_env!(ctx.context.clone()); ctx.contract.account_storage_fee(); ctx.contract.total_registered_accounts(); ctx.contract .lookup_account(ValidAccountId::try_from(ctx.account_id).unwrap()); } }
use crate::{ event::metric::{Metric, MetricKind, MetricValue}, shutdown::ShutdownSignal, topology::config::{DataType, GlobalOptions, SourceConfig, SourceDescription}, Event, }; use chrono::Utc; use futures::{ compat::Future01CompatExt, future::{FutureExt, TryFutureExt}, stream::StreamExt, }; use futures01::{sync::mpsc, Future, Sink}; use metrics_core::Key; use metrics_runtime::{Controller, Measurement}; use serde::{Deserialize, Serialize}; use std::{collections::BTreeMap, time::Duration}; use tokio::time::interval; #[derive(Deserialize, Serialize, Debug, Clone, Default)] pub struct InternalMetricsConfig; inventory::submit! { SourceDescription::new::<InternalMetricsConfig>("internal_metrics") } #[typetag::serde(name = "internal_metrics")] impl SourceConfig for InternalMetricsConfig { fn build( &self, _name: &str, _globals: &GlobalOptions, shutdown: ShutdownSignal, out: mpsc::Sender<Event>, ) -> crate::Result<super::Source> { let fut = run(get_controller()?, out, shutdown).boxed().compat(); Ok(Box::new(fut)) } fn output_type(&self) -> DataType { DataType::Metric } fn source_type(&self) -> &'static str { "internal_metrics" } } fn get_controller() -> crate::Result<Controller> { crate::metrics::CONTROLLER .get() .cloned() .ok_or_else(|| "metrics system not initialized".into()) } async fn run( controller: Controller, mut out: mpsc::Sender<Event>, mut shutdown: ShutdownSignal, ) -> Result<(), ()> { let mut interval = interval(Duration::from_secs(2)).map(|_| ()); while let Some(()) = interval.next().await { // Check for shutdown signal if shutdown.poll().expect("polling shutdown").is_ready() { break; } let metrics = capture_metrics(&controller); let (sink, _) = out .send_all(futures01::stream::iter_ok(metrics)) .compat() .await .map_err(|error| error!(message = "error sending internal metrics", %error))?; out = sink; } Ok(()) } fn capture_metrics(controller: &Controller) -> impl Iterator<Item = Event> { controller .snapshot() .into_measurements() .into_iter() .map(|(k, m)| into_event(k, m)) } fn into_event(key: Key, measurement: Measurement) -> Event { let value = match measurement { Measurement::Counter(v) => MetricValue::Counter { value: v as f64 }, Measurement::Gauge(v) => MetricValue::Gauge { value: v as f64 }, Measurement::Histogram(packed) => { let values = packed .decompress() .into_iter() .map(|i| i as f64) .collect::<Vec<_>>(); let sample_rates = vec![1; values.len()]; MetricValue::Distribution { values, sample_rates, } } }; let labels = key .labels() .map(|label| (String::from(label.key()), String::from(label.value()))) .collect::<BTreeMap<_, _>>(); let metric = Metric { name: key.name().to_string(), timestamp: Some(Utc::now()), tags: if labels.is_empty() { None } else { Some(labels) }, kind: MetricKind::Absolute, value, }; Event::Metric(metric) } #[cfg(test)] mod tests { use super::{capture_metrics, get_controller}; use crate::event::metric::{Metric, MetricValue}; use metrics::{counter, gauge, timing, value}; use std::collections::BTreeMap; #[test] fn captures_internal_metrics() { crate::metrics::init().unwrap(); // There *seems* to be a race condition here (CI was flaky), so add a slight delay. std::thread::sleep(std::time::Duration::from_millis(300)); gauge!("foo", 1); gauge!("foo", 2); counter!("bar", 3); counter!("bar", 4); timing!("baz", 5); timing!("baz", 6); value!("quux", 7, "host" => "foo"); value!("quux", 8, "host" => "foo"); let controller = get_controller().expect("no controller"); // There *seems* to be a race condition here (CI was flaky), so add a slight delay. std::thread::sleep(std::time::Duration::from_millis(300)); let output = capture_metrics(&controller) .map(|event| { let m = event.into_metric(); (m.name.clone(), m) }) .collect::<BTreeMap<String, Metric>>(); assert_eq!(MetricValue::Gauge { value: 2.0 }, output["foo"].value); assert_eq!(MetricValue::Counter { value: 7.0 }, output["bar"].value); assert_eq!( MetricValue::Distribution { values: vec![5.0, 6.0], sample_rates: vec![1, 1] }, output["baz"].value ); assert_eq!( MetricValue::Distribution { values: vec![7.0, 8.0], sample_rates: vec![1, 1] }, output["quux"].value ); let mut labels = BTreeMap::new(); labels.insert(String::from("host"), String::from("foo")); assert_eq!(Some(labels), output["quux"].tags); } }
use pickledb::{PickleDb, PickleDbDumpPolicy, SerializationMethod}; use std::time::Duration; use std::{thread, time}; mod common; #[cfg(test)] extern crate rstest; use rstest::rstest_parametrize; #[rstest_parametrize(ser_method_int, case(0), case(1), case(2), case(3))] fn auto_dump_policy_test(ser_method_int: i32) { test_setup!("auto_dump_policy_test", ser_method_int, db_name); // create a DB with AutoDump policy let mut db = PickleDb::new( &db_name, PickleDbDumpPolicy::AutoDump, ser_method!(ser_method_int), ); // set a key-value pair assert!(db.set("key1", &1).is_ok()); // verify the change in the DB { let read_db = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); assert_eq!(read_db.get::<i32>("key1").unwrap(), 1); } // remove a key assert!(db.rem("key1").unwrap_or(false)); // verify the change in the DB { let read_db = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); assert!(read_db.get::<i32>("key1").is_none()); } // create a list assert!(db.lcreate("list1").is_ok()); // verify the change in the DB { let read_db = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); assert!(read_db.exists("list1")); assert_eq!(read_db.llen("list1"), 0); } // add values to list db.lextend("list1", &[1, 2, 3]); // verify the change in the DB { let read_db = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); assert_eq!(read_db.llen("list1"), 3); } // pop an item from a list db.lpop::<i32>("list1", 0); // verify the change in the DB { let read_db = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); assert_eq!(read_db.llen("list1"), 2); } // remove an item from a list assert!(db.lrem_value("list1", &2).unwrap_or(false)); // verify the change in the DB { let read_db = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); assert_eq!(read_db.llen("list1"), 1); } // remove a list db.lrem_list("list1").unwrap(); // verify the change in the DB { let read_db = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); assert!(!read_db.exists("list1")); } } #[rstest_parametrize(ser_method_int, case(0), case(1), case(2), case(3))] fn read_only_policy_test(ser_method_int: i32) { test_setup!("read_only_policy_test", ser_method_int, db_name); // create a DB and set a value let mut db = PickleDb::new( &db_name, PickleDbDumpPolicy::AutoDump, ser_method!(ser_method_int), ); assert!(db.set("key1", &String::from("value1")).is_ok()); // create a read only instance of the same DB let mut read_db1 = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); // set a key-value pair in the read-only DB assert!(read_db1.set("key2", &String::from("value2")).is_ok()); assert!(read_db1.exists("key2")); // verify the change isn't dumped to the file { let read_db2 = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); assert!(read_db2.exists("key1")); assert!(!read_db2.exists("key2")); } // try to dump data to the file assert!(read_db1.dump().is_ok()); // verify the change isn't dumped to the file { let read_db2 = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); assert!(read_db2.exists("key1")); assert!(!read_db2.exists("key2")); } // drop the DB drop(read_db1); // verify the change isn't dumped to the file { let read_db2 = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); assert!(read_db2.exists("key1")); assert!(!read_db2.exists("key2")); } } #[rstest_parametrize(ser_method_int, case(0), case(1), case(2), case(3))] fn dump_upon_request_policy_test(ser_method_int: i32) { test_setup!("dump_upon_request_policy_test", ser_method_int, db_name); // create a DB and set a value let mut db = PickleDb::new( &db_name, PickleDbDumpPolicy::DumpUponRequest, ser_method!(ser_method_int), ); assert!(db.set("key1", &String::from("value1")).is_ok()); // verify file is not yet created assert!(PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).is_err()); // dump to file assert!(db.dump().is_ok()); // verify the change is dumped to the file { let read_db = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); assert!(read_db.exists("key1")); } // set another key assert!(db.set("key2", &String::from("value2")).is_ok()); // drop DB object drop(db); // verify the change is not dumped to the file { let read_db = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); assert!(read_db.exists("key1")); assert!(!read_db.exists("key2")); } } #[rstest_parametrize(ser_method_int, case(0), case(1), case(2), case(3))] fn periodic_dump_policy_test(ser_method_int: i32) { test_setup!("periodic_dump_policy_test", ser_method_int, db_name); // create a DB and set a value let mut db = PickleDb::new( &db_name, PickleDbDumpPolicy::PeriodicDump(Duration::new(1, 0)), ser_method!(ser_method_int), ); assert!(db.set("key1", &String::from("value1")).is_ok()); // verify file is not yet created assert!(PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).is_err()); // sleep for 0.5 sec thread::sleep(time::Duration::from_millis(500)); // verify file is not yet created assert!(PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).is_err()); // sleep for 0.55 sec thread::sleep(time::Duration::from_millis(550)); // make another change in the DB assert!(db.set("key2", &String::from("value2")).is_ok()); // verify the change is dumped to the file { let read_db = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); assert!(read_db.exists("key1")); assert!(read_db.exists("key2")); } // make another change in the DB assert!(db.set("key3", &String::from("value3")).is_ok()); // verify the change is not yet dumped to the file { let read_db = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); assert!(!read_db.exists("key3")); } // dumb DB to file assert!(db.dump().is_ok()); // verify the change is now dumped to the file { let read_db = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); assert!(read_db.exists("key3")); } // sleep for 1 more second thread::sleep(time::Duration::from_secs(1)); // make another change in the DB assert!(db.set("key4", &String::from("value4")).is_ok()); // verify the change is dumped to the file { let read_db = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); assert!(read_db.exists("key4")); } // make another change in the DB assert!(db.set("key5", &String::from("value5")).is_ok()); // drop DB and verify change is written to DB drop(db); // verify the change is dumped to the file { let read_db = PickleDb::load_read_only(&db_name, ser_method!(ser_method_int)).unwrap(); assert!(read_db.exists("key5")); } }
use crate::decode::Decode; use crate::encode::{Encode, IsNull}; use crate::error::BoxDynError; use crate::mssql::io::MssqlBufMutExt; use crate::mssql::protocol::type_info::{Collation, CollationFlags, DataType, TypeInfo}; use crate::mssql::{Mssql, MssqlTypeInfo, MssqlValueRef}; use crate::types::Type; use std::borrow::Cow; impl Type<Mssql> for str { fn type_info() -> MssqlTypeInfo { MssqlTypeInfo(TypeInfo::new(DataType::NVarChar, 0)) } fn compatible(ty: &MssqlTypeInfo) -> bool { matches!( ty.0.ty, DataType::NVarChar | DataType::NChar | DataType::BigVarChar | DataType::VarChar | DataType::BigChar | DataType::Char ) } } impl Type<Mssql> for String { fn type_info() -> MssqlTypeInfo { <str as Type<Mssql>>::type_info() } fn compatible(ty: &MssqlTypeInfo) -> bool { <str as Type<Mssql>>::compatible(ty) } } impl Encode<'_, Mssql> for &'_ str { fn produces(&self) -> Option<MssqlTypeInfo> { // an empty string needs to be encoded as `nvarchar(2)` Some(MssqlTypeInfo(TypeInfo { ty: DataType::NVarChar, size: ((self.len() * 2) as u32).max(2), scale: 0, precision: 0, collation: Some(Collation { locale: 1033, flags: CollationFlags::IGNORE_CASE | CollationFlags::IGNORE_WIDTH | CollationFlags::IGNORE_KANA, sort: 52, version: 0, }), })) } fn encode_by_ref(&self, buf: &mut Vec<u8>) -> IsNull { buf.put_utf16_str(self); IsNull::No } } impl Encode<'_, Mssql> for String { fn produces(&self) -> Option<MssqlTypeInfo> { <&str as Encode<Mssql>>::produces(&self.as_str()) } fn encode_by_ref(&self, buf: &mut Vec<u8>) -> IsNull { <&str as Encode<Mssql>>::encode_by_ref(&self.as_str(), buf) } } impl Decode<'_, Mssql> for String { fn decode(value: MssqlValueRef<'_>) -> Result<Self, BoxDynError> { Ok(value .type_info .0 .encoding()? .decode_without_bom_handling(value.as_bytes()?) .0 .into_owned()) } } impl Type<Mssql> for Cow<'_, str> { fn type_info() -> MssqlTypeInfo { <&str as Type<Mssql>>::type_info() } fn compatible(ty: &MssqlTypeInfo) -> bool { <&str as Type<Mssql>>::compatible(ty) } } impl Encode<'_, Mssql> for Cow<'_, str> { fn produces(&self) -> Option<MssqlTypeInfo> { match self { Cow::Borrowed(str) => <&str as Encode<Mssql>>::produces(str), Cow::Owned(str) => <&str as Encode<Mssql>>::produces(&(str.as_ref())), } } fn encode_by_ref(&self, buf: &mut Vec<u8>) -> IsNull { match self { Cow::Borrowed(str) => <&str as Encode<Mssql>>::encode_by_ref(str, buf), Cow::Owned(str) => <&str as Encode<Mssql>>::encode_by_ref(&(str.as_ref()), buf), } } } impl<'r> Decode<'r, Mssql> for Cow<'r, str> { fn decode(value: MssqlValueRef<'r>) -> Result<Self, BoxDynError> { Ok(Cow::Owned( value .type_info .0 .encoding()? .decode_without_bom_handling(value.as_bytes()?) .0 .into_owned(), )) } }
fn main() { // This test validates that IMap pulls in its dependencies including IIterator and IKeyValuePair. // This is a particularly interesting test because IMap only mentions IKeyValuePair indirectly // through its interface requirement on the specialization of IIterable. windows::core::build_legacy! { Windows::Foundation::Collections::IMap, }; }
extern crate pest; #[macro_use] extern crate pest_derive; use parser::parse; use std::env; use std::fs::File; use std::io::prelude::*; use tokenizer::tokenize; mod tokenizer; mod parser; mod stdlib; fn main() { let args: Vec<String> = env::args().collect(); if args.get(0).is_none() { eprintln!("Please provide file name as parameter"); panic!(); } let contents = read_file(args.get(1).unwrap()); let tokens = tokenize(&contents); if tokens.is_err() { let errors = tokens.err().unwrap(); errors.iter().for_each(|err| eprintln!("ERROR: {}", err)); panic!() } parse(contents); } fn read_file(name: &str) -> String { let mut fo = File::open(name).expect("File not found!"); let mut contents = String::new(); fo.read_to_string(&mut contents).expect("Something went wrong while reading"); contents }
//error-pattern:no clauses match fn main() { #macro([#trivial(), 1*2*4*2*1]); assert(#trivial(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16) == 16); }
use super::ast_utils::*; use super::type_printer::print_type; pub fn print_at_depth (s: String, depth: isize) { let mut str = String::from(""); for _ in 0..depth * 4 { str += &String::from(" "); } str += &s; eprintln!("{}", str); } pub fn print_ast_node (node: &ASTNode, depth: isize) { match node { ASTNode::IntegerLiteral(int) => { print_at_depth(format!("Integer literal: {}", int), depth) }, ASTNode::Identifier(ident) => { print_at_depth(format!("Identifier: {}", ident), depth) }, ASTNode::ReturnStatement(ret_stmt) => { print_at_depth(format!("Return:"), depth); print_ast_node(ret_stmt.as_ref(), depth + 1) }, ASTNode::BlockStatement(block) => { print_at_depth("Block:".to_string(), depth); for stmt in block { print_ast_node(stmt, depth + 1) } }, ASTNode::FunctionDefinition(func) => { print_at_depth(format!("Function: {}", func.name), depth); if func.params.len() > 0 { print_at_depth("Parameters:".to_string(), depth + 1); for param in &func.params { print_at_depth(format!("- \"{}\"", param.name), depth + 2); print_type(&param.param_type, depth + 3); } } if let Some(body) = &func.body { print_at_depth("Body:".to_string(), depth + 1); for stmt in body { print_ast_node(stmt, depth + 2) } } } ASTNode::UnaryOperation(unar) => { print_at_depth(format!("Unary operation: {}", unar.operator), depth); print_ast_node(&unar.operand, depth + 1); } ASTNode::BinaryOperation(bin) => { print_at_depth(format!("Binary operation: {}", bin.operator), depth); print_ast_node(&bin.left_side, depth + 1); print_ast_node(&bin.right_side, depth + 1) } ASTNode::VariableDeclaration(var) => { print_at_depth(format!("Variable declaration: {}", var.identifier), depth); print_type(&var.var_type, depth + 1); if let Some(val) = &var.initial_value { print_at_depth("Initial value:".to_string(), depth + 1); print_ast_node(val, depth + 2); } } ASTNode::IfStatement(if_stmt) => { print_at_depth("If statement:".to_string(), depth); print_at_depth("Condition:".to_string(), depth + 1); print_ast_node(&if_stmt.condition, depth + 2); print_at_depth("Body:".to_string(), depth + 1); print_ast_node(&if_stmt.body, depth + 2); if let Some(else_stmt) = &if_stmt.else_stmt { print_at_depth("Else:".to_string(), depth + 1); print_ast_node(else_stmt, depth + 2); } }, ASTNode::FunctionCall(func_call) => { print_at_depth(format!("Function call: {}", func_call.name), depth); for arg in &func_call.args { print_ast_node(arg, depth + 1); } }, ASTNode::WhileLoop(while_loop) => { print_at_depth("While loop:".to_string(), depth); print_at_depth("Condition:".to_string(), depth + 1); print_ast_node(&while_loop.condition, depth + 2); print_at_depth("Body:".to_string(), depth + 1); print_ast_node(&while_loop.body, depth + 2); }, ASTNode::ForLoop(for_loop) => { // These are complicated AST nodes :) print_at_depth("For loop:".to_string(), depth); if let Some(declaration) = &for_loop.declaration { print_at_depth("Declaration:".to_string(), depth + 1); print_ast_node(declaration, depth + 2); } if let Some(condition) = &for_loop.condition { print_at_depth("Condition".to_string(), depth + 1); print_ast_node(condition, depth + 2); } if let Some(modification) = &for_loop.modification { print_at_depth("Modification:".to_string(), depth + 1); print_ast_node(modification, depth + 2); } print_at_depth("Body:".to_string(), depth + 1); print_ast_node(&for_loop.body, depth + 2); }, ASTNode::StringLiteral(st) => { print_at_depth(format!("String: \"{}\"", st), depth); } } }
fn main() { println!("Damn, that's so cool!"); }
#[cfg(feature = "ffi")] use std::env; fn main() { #[cfg(feature = "ffi")] link_search(); } #[cfg(feature = "ffi")] fn link_search() { let manifest = env!("CARGO_MANIFEST_DIR"); if cfg!(target_os = "windows") { println!(r"cargo:rustc-link-search={}/libraries/Win/x64", manifest); } else if cfg!(target_os = "macos") { println!( r"cargo:rustc-link-search=framework={}/libraries/Mac", manifest ); } else if cfg!(target_os = "linux") { println!(r"cargo:rustc-link-search={}/libraries/Linux", manifest); } } #[cfg(any())] fn run_bindgen() { let bindings = bindgen::Builder::default() .clang_arg("--language=c++") // .clang_arg("-std=c++14") .clang_arg("-std=c++1y") .clang_arg("-stdlib=libc++") .header("headers/FMWrapper.h") .parse_callbacks(Box::new(bindgen::CargoCallbacks)) .generate() .expect("Unable to generate bindings"); bindings .write_to_file("bindings.rs") .expect("Couldn't write bindings!"); }
// auto generated, do not modify. // created: Mon Feb 22 23:57:02 2016 // src-file: /QtWidgets/qdialogbuttonbox.h // dst-file: /src/widgets/qdialogbuttonbox.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use super::qwidget::*; // 773 use std::ops::Deref; // use super::qlist::*; // 775 use super::super::core::qstring::*; // 771 use super::qabstractbutton::*; // 773 use super::super::core::qobjectdefs::*; // 771 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QDialogButtonBox_Class_Size() -> c_int; // proto: QList<QAbstractButton *> QDialogButtonBox::buttons(); fn C_ZNK16QDialogButtonBox7buttonsEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QDialogButtonBox::setCenterButtons(bool center); fn C_ZN16QDialogButtonBox16setCenterButtonsEb(qthis: u64 /* *mut c_void*/, arg0: c_char); // proto: bool QDialogButtonBox::centerButtons(); fn C_ZNK16QDialogButtonBox13centerButtonsEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: const QMetaObject * QDialogButtonBox::metaObject(); fn C_ZNK16QDialogButtonBox10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QDialogButtonBox::removeButton(QAbstractButton * button); fn C_ZN16QDialogButtonBox12removeButtonEP15QAbstractButton(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QDialogButtonBox::~QDialogButtonBox(); fn C_ZN16QDialogButtonBoxD2Ev(qthis: u64 /* *mut c_void*/); // proto: void QDialogButtonBox::QDialogButtonBox(QWidget * parent); fn C_ZN16QDialogButtonBoxC2EP7QWidget(arg0: *mut c_void) -> u64; // proto: void QDialogButtonBox::clear(); fn C_ZN16QDialogButtonBox5clearEv(qthis: u64 /* *mut c_void*/); fn QDialogButtonBox_SlotProxy_connect__ZN16QDialogButtonBox8acceptedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QDialogButtonBox_SlotProxy_connect__ZN16QDialogButtonBox13helpRequestedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QDialogButtonBox_SlotProxy_connect__ZN16QDialogButtonBox7clickedEP15QAbstractButton(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); fn QDialogButtonBox_SlotProxy_connect__ZN16QDialogButtonBox8rejectedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); } // <= ext block end // body block begin => // class sizeof(QDialogButtonBox)=1 #[derive(Default)] pub struct QDialogButtonBox { qbase: QWidget, pub qclsinst: u64 /* *mut c_void*/, pub _helpRequested: QDialogButtonBox_helpRequested_signal, pub _accepted: QDialogButtonBox_accepted_signal, pub _clicked: QDialogButtonBox_clicked_signal, pub _rejected: QDialogButtonBox_rejected_signal, } impl /*struct*/ QDialogButtonBox { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QDialogButtonBox { return QDialogButtonBox{qbase: QWidget::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QDialogButtonBox { type Target = QWidget; fn deref(&self) -> &QWidget { return & self.qbase; } } impl AsRef<QWidget> for QDialogButtonBox { fn as_ref(& self) -> & QWidget { return & self.qbase; } } // proto: QList<QAbstractButton *> QDialogButtonBox::buttons(); impl /*struct*/ QDialogButtonBox { pub fn buttons<RetType, T: QDialogButtonBox_buttons<RetType>>(& self, overload_args: T) -> RetType { return overload_args.buttons(self); // return 1; } } pub trait QDialogButtonBox_buttons<RetType> { fn buttons(self , rsthis: & QDialogButtonBox) -> RetType; } // proto: QList<QAbstractButton *> QDialogButtonBox::buttons(); impl<'a> /*trait*/ QDialogButtonBox_buttons<u64> for () { fn buttons(self , rsthis: & QDialogButtonBox) -> u64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK16QDialogButtonBox7buttonsEv()}; let mut ret = unsafe {C_ZNK16QDialogButtonBox7buttonsEv(rsthis.qclsinst)}; return ret as u64; // 5 // return 1; } } // proto: void QDialogButtonBox::setCenterButtons(bool center); impl /*struct*/ QDialogButtonBox { pub fn setCenterButtons<RetType, T: QDialogButtonBox_setCenterButtons<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setCenterButtons(self); // return 1; } } pub trait QDialogButtonBox_setCenterButtons<RetType> { fn setCenterButtons(self , rsthis: & QDialogButtonBox) -> RetType; } // proto: void QDialogButtonBox::setCenterButtons(bool center); impl<'a> /*trait*/ QDialogButtonBox_setCenterButtons<()> for (i8) { fn setCenterButtons(self , rsthis: & QDialogButtonBox) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN16QDialogButtonBox16setCenterButtonsEb()}; let arg0 = self as c_char; unsafe {C_ZN16QDialogButtonBox16setCenterButtonsEb(rsthis.qclsinst, arg0)}; // return 1; } } // proto: bool QDialogButtonBox::centerButtons(); impl /*struct*/ QDialogButtonBox { pub fn centerButtons<RetType, T: QDialogButtonBox_centerButtons<RetType>>(& self, overload_args: T) -> RetType { return overload_args.centerButtons(self); // return 1; } } pub trait QDialogButtonBox_centerButtons<RetType> { fn centerButtons(self , rsthis: & QDialogButtonBox) -> RetType; } // proto: bool QDialogButtonBox::centerButtons(); impl<'a> /*trait*/ QDialogButtonBox_centerButtons<i8> for () { fn centerButtons(self , rsthis: & QDialogButtonBox) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK16QDialogButtonBox13centerButtonsEv()}; let mut ret = unsafe {C_ZNK16QDialogButtonBox13centerButtonsEv(rsthis.qclsinst)}; return ret as i8; // 1 // return 1; } } // proto: const QMetaObject * QDialogButtonBox::metaObject(); impl /*struct*/ QDialogButtonBox { pub fn metaObject<RetType, T: QDialogButtonBox_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QDialogButtonBox_metaObject<RetType> { fn metaObject(self , rsthis: & QDialogButtonBox) -> RetType; } // proto: const QMetaObject * QDialogButtonBox::metaObject(); impl<'a> /*trait*/ QDialogButtonBox_metaObject<QMetaObject> for () { fn metaObject(self , rsthis: & QDialogButtonBox) -> QMetaObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK16QDialogButtonBox10metaObjectEv()}; let mut ret = unsafe {C_ZNK16QDialogButtonBox10metaObjectEv(rsthis.qclsinst)}; let mut ret1 = QMetaObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QDialogButtonBox::removeButton(QAbstractButton * button); impl /*struct*/ QDialogButtonBox { pub fn removeButton<RetType, T: QDialogButtonBox_removeButton<RetType>>(& self, overload_args: T) -> RetType { return overload_args.removeButton(self); // return 1; } } pub trait QDialogButtonBox_removeButton<RetType> { fn removeButton(self , rsthis: & QDialogButtonBox) -> RetType; } // proto: void QDialogButtonBox::removeButton(QAbstractButton * button); impl<'a> /*trait*/ QDialogButtonBox_removeButton<()> for (&'a QAbstractButton) { fn removeButton(self , rsthis: & QDialogButtonBox) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN16QDialogButtonBox12removeButtonEP15QAbstractButton()}; let arg0 = self.qclsinst as *mut c_void; unsafe {C_ZN16QDialogButtonBox12removeButtonEP15QAbstractButton(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QDialogButtonBox::~QDialogButtonBox(); impl /*struct*/ QDialogButtonBox { pub fn free<RetType, T: QDialogButtonBox_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QDialogButtonBox_free<RetType> { fn free(self , rsthis: & QDialogButtonBox) -> RetType; } // proto: void QDialogButtonBox::~QDialogButtonBox(); impl<'a> /*trait*/ QDialogButtonBox_free<()> for () { fn free(self , rsthis: & QDialogButtonBox) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN16QDialogButtonBoxD2Ev()}; unsafe {C_ZN16QDialogButtonBoxD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: void QDialogButtonBox::QDialogButtonBox(QWidget * parent); impl /*struct*/ QDialogButtonBox { pub fn new<T: QDialogButtonBox_new>(value: T) -> QDialogButtonBox { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QDialogButtonBox_new { fn new(self) -> QDialogButtonBox; } // proto: void QDialogButtonBox::QDialogButtonBox(QWidget * parent); impl<'a> /*trait*/ QDialogButtonBox_new for (Option<&'a QWidget>) { fn new(self) -> QDialogButtonBox { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN16QDialogButtonBoxC2EP7QWidget()}; let ctysz: c_int = unsafe{QDialogButtonBox_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void; let qthis: u64 = unsafe {C_ZN16QDialogButtonBoxC2EP7QWidget(arg0)}; let rsthis = QDialogButtonBox{qbase: QWidget::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QDialogButtonBox::clear(); impl /*struct*/ QDialogButtonBox { pub fn clear<RetType, T: QDialogButtonBox_clear<RetType>>(& self, overload_args: T) -> RetType { return overload_args.clear(self); // return 1; } } pub trait QDialogButtonBox_clear<RetType> { fn clear(self , rsthis: & QDialogButtonBox) -> RetType; } // proto: void QDialogButtonBox::clear(); impl<'a> /*trait*/ QDialogButtonBox_clear<()> for () { fn clear(self , rsthis: & QDialogButtonBox) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN16QDialogButtonBox5clearEv()}; unsafe {C_ZN16QDialogButtonBox5clearEv(rsthis.qclsinst)}; // return 1; } } #[derive(Default)] // for QDialogButtonBox_helpRequested pub struct QDialogButtonBox_helpRequested_signal{poi:u64} impl /* struct */ QDialogButtonBox { pub fn helpRequested(&self) -> QDialogButtonBox_helpRequested_signal { return QDialogButtonBox_helpRequested_signal{poi:self.qclsinst}; } } impl /* struct */ QDialogButtonBox_helpRequested_signal { pub fn connect<T: QDialogButtonBox_helpRequested_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QDialogButtonBox_helpRequested_signal_connect { fn connect(self, sigthis: QDialogButtonBox_helpRequested_signal); } #[derive(Default)] // for QDialogButtonBox_accepted pub struct QDialogButtonBox_accepted_signal{poi:u64} impl /* struct */ QDialogButtonBox { pub fn accepted(&self) -> QDialogButtonBox_accepted_signal { return QDialogButtonBox_accepted_signal{poi:self.qclsinst}; } } impl /* struct */ QDialogButtonBox_accepted_signal { pub fn connect<T: QDialogButtonBox_accepted_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QDialogButtonBox_accepted_signal_connect { fn connect(self, sigthis: QDialogButtonBox_accepted_signal); } #[derive(Default)] // for QDialogButtonBox_clicked pub struct QDialogButtonBox_clicked_signal{poi:u64} impl /* struct */ QDialogButtonBox { pub fn clicked(&self) -> QDialogButtonBox_clicked_signal { return QDialogButtonBox_clicked_signal{poi:self.qclsinst}; } } impl /* struct */ QDialogButtonBox_clicked_signal { pub fn connect<T: QDialogButtonBox_clicked_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QDialogButtonBox_clicked_signal_connect { fn connect(self, sigthis: QDialogButtonBox_clicked_signal); } #[derive(Default)] // for QDialogButtonBox_rejected pub struct QDialogButtonBox_rejected_signal{poi:u64} impl /* struct */ QDialogButtonBox { pub fn rejected(&self) -> QDialogButtonBox_rejected_signal { return QDialogButtonBox_rejected_signal{poi:self.qclsinst}; } } impl /* struct */ QDialogButtonBox_rejected_signal { pub fn connect<T: QDialogButtonBox_rejected_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QDialogButtonBox_rejected_signal_connect { fn connect(self, sigthis: QDialogButtonBox_rejected_signal); } // accepted() extern fn QDialogButtonBox_accepted_signal_connect_cb_0(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QDialogButtonBox_accepted_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QDialogButtonBox_accepted_signal_connect for fn() { fn connect(self, sigthis: QDialogButtonBox_accepted_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QDialogButtonBox_accepted_signal_connect_cb_0 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QDialogButtonBox_SlotProxy_connect__ZN16QDialogButtonBox8acceptedEv(arg0, arg1, arg2)}; } } impl /* trait */ QDialogButtonBox_accepted_signal_connect for Box<Fn()> { fn connect(self, sigthis: QDialogButtonBox_accepted_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QDialogButtonBox_accepted_signal_connect_cb_box_0 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QDialogButtonBox_SlotProxy_connect__ZN16QDialogButtonBox8acceptedEv(arg0, arg1, arg2)}; } } // helpRequested() extern fn QDialogButtonBox_helpRequested_signal_connect_cb_1(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QDialogButtonBox_helpRequested_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QDialogButtonBox_helpRequested_signal_connect for fn() { fn connect(self, sigthis: QDialogButtonBox_helpRequested_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QDialogButtonBox_helpRequested_signal_connect_cb_1 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QDialogButtonBox_SlotProxy_connect__ZN16QDialogButtonBox13helpRequestedEv(arg0, arg1, arg2)}; } } impl /* trait */ QDialogButtonBox_helpRequested_signal_connect for Box<Fn()> { fn connect(self, sigthis: QDialogButtonBox_helpRequested_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QDialogButtonBox_helpRequested_signal_connect_cb_box_1 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QDialogButtonBox_SlotProxy_connect__ZN16QDialogButtonBox13helpRequestedEv(arg0, arg1, arg2)}; } } // clicked(class QAbstractButton *) extern fn QDialogButtonBox_clicked_signal_connect_cb_2(rsfptr:fn(QAbstractButton), arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsarg0 = QAbstractButton::inheritFrom(arg0 as u64); rsfptr(rsarg0); } extern fn QDialogButtonBox_clicked_signal_connect_cb_box_2(rsfptr_raw:*mut Box<Fn(QAbstractButton)>, arg0: *mut c_void) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = QAbstractButton::inheritFrom(arg0 as u64); // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QDialogButtonBox_clicked_signal_connect for fn(QAbstractButton) { fn connect(self, sigthis: QDialogButtonBox_clicked_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QDialogButtonBox_clicked_signal_connect_cb_2 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QDialogButtonBox_SlotProxy_connect__ZN16QDialogButtonBox7clickedEP15QAbstractButton(arg0, arg1, arg2)}; } } impl /* trait */ QDialogButtonBox_clicked_signal_connect for Box<Fn(QAbstractButton)> { fn connect(self, sigthis: QDialogButtonBox_clicked_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QDialogButtonBox_clicked_signal_connect_cb_box_2 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QDialogButtonBox_SlotProxy_connect__ZN16QDialogButtonBox7clickedEP15QAbstractButton(arg0, arg1, arg2)}; } } // rejected() extern fn QDialogButtonBox_rejected_signal_connect_cb_3(rsfptr:fn(), ) { println!("{}:{}", file!(), line!()); rsfptr(); } extern fn QDialogButtonBox_rejected_signal_connect_cb_box_3(rsfptr_raw:*mut Box<Fn()>, ) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; // rsfptr(); unsafe{(*rsfptr_raw)()}; } impl /* trait */ QDialogButtonBox_rejected_signal_connect for fn() { fn connect(self, sigthis: QDialogButtonBox_rejected_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QDialogButtonBox_rejected_signal_connect_cb_3 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QDialogButtonBox_SlotProxy_connect__ZN16QDialogButtonBox8rejectedEv(arg0, arg1, arg2)}; } } impl /* trait */ QDialogButtonBox_rejected_signal_connect for Box<Fn()> { fn connect(self, sigthis: QDialogButtonBox_rejected_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QDialogButtonBox_rejected_signal_connect_cb_box_3 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QDialogButtonBox_SlotProxy_connect__ZN16QDialogButtonBox8rejectedEv(arg0, arg1, arg2)}; } } // <= body block end
// Copyright (c) 2016 DWANGO Co., Ltd. All Rights Reserved. // See the LICENSE file at the top-level directory of this distribution. //! Fiber related components (for developers). //! //! Those are mainly exported for developers. //! So, usual users do not need to be conscious. use std::fmt; use std::sync::Arc; use std::sync::atomic::{self, AtomicUsize}; use futures::{self, Async, Future, BoxFuture, IntoFuture}; pub use self::schedule::{Scheduler, SchedulerHandle, SchedulerId}; pub use self::schedule::{with_current_context, Context}; use sync::oneshot::{self, Monitor}; use internal::fiber::Task; mod schedule; /// The identifier of a fiber. /// /// The value is unique among the live fibers in a scheduler. pub type FiberId = usize; /// The identifier of an execution context. pub type ContextId = (SchedulerId, FiberId); /// The `Spawn` trait allows for spawning fibers. pub trait Spawn { /// Spawns a fiber which will execute given boxed future. fn spawn_boxed(&self, fiber: BoxFuture<(), ()>); /// Spawns a fiber which will execute given future. fn spawn<F>(&self, fiber: F) where F: Future<Item = (), Error = ()> + Send + 'static { self.spawn_boxed(fiber.boxed()); } /// Equivalent to `self.spawn(futures::lazy(|| f()))`. fn spawn_fn<F, T>(&self, f: F) where F: FnOnce() -> T + Send + 'static, T: IntoFuture<Item = (), Error = ()> + Send + 'static, T::Future: Send { self.spawn(futures::lazy(|| f())) } /// Spawns a fiber and returns a future to monitor it's execution result. fn spawn_monitor<F, T, E>(&self, f: F) -> Monitor<T, E> where F: Future<Item = T, Error = E> + Send + 'static, T: Send + 'static, E: Send + 'static { let (monitored, monitor) = oneshot::monitor(); self.spawn(f.then(move |r| Ok(monitored.exit(r)))); monitor } /// Converts this instance into a boxed object. fn boxed(self) -> BoxSpawn where Self: Sized + Send + 'static { BoxSpawn(Box::new(move |fiber| self.spawn_boxed(fiber))) } } /// Boxed `Spawn` object. pub struct BoxSpawn(Box<Fn(BoxFuture<(), ()>) + Send + 'static>); impl Spawn for BoxSpawn { fn spawn_boxed(&self, fiber: BoxFuture<(), ()>) { (self.0)(fiber); } } impl fmt::Debug for BoxSpawn { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "BoxSpawn(_)") } } #[derive(Debug)] struct FiberState { pub fiber_id: FiberId, task: Task, parks: usize, unparks: Arc<AtomicUsize>, pub in_run_queue: bool, } impl FiberState { pub fn new(fiber_id: FiberId, task: Task) -> Self { FiberState { fiber_id: fiber_id, task: task, parks: 0, unparks: Arc::new(AtomicUsize::new(0)), in_run_queue: false, } } pub fn run_once(&mut self) -> bool { if self.parks > 0 { if self.unparks.load(atomic::Ordering::SeqCst) > 0 { self.parks -= 1; self.unparks.fetch_sub(1, atomic::Ordering::SeqCst); } } if let Ok(Async::NotReady) = self.task.0.poll() { false } else { true } } pub fn is_runnable(&self) -> bool { self.parks == 0 || self.unparks.load(atomic::Ordering::SeqCst) > 0 } pub fn park(&mut self, scheduler_id: schedule::SchedulerId, scheduler: schedule::SchedulerHandle) -> Unpark { self.parks += 1; Unpark { fiber_id: self.fiber_id, unparks: self.unparks.clone(), scheduler_id: scheduler_id, scheduler: scheduler, } } } /// Unpark object. /// /// When this object is dropped, it unparks the associated fiber. /// /// This is created by calling `Context::park` method. #[derive(Debug)] pub struct Unpark { fiber_id: FiberId, unparks: Arc<AtomicUsize>, scheduler_id: schedule::SchedulerId, scheduler: schedule::SchedulerHandle, } impl Unpark { /// Returns the identifier of the context on which this object was created. pub fn context_id(&self) -> ContextId { (self.scheduler_id, self.fiber_id) } } impl Drop for Unpark { fn drop(&mut self) { let old = self.unparks.fetch_add(1, atomic::Ordering::SeqCst); if old == 0 { self.scheduler.wakeup(self.fiber_id); } } }
use std::fmt; use std::time::Duration; use hyper::Client; use hyper::Url; use hyper::header::Connection; use hyper::status::StatusCode; use hyper::client::RedirectPolicy; use stopwatch::Stopwatch; use time::Duration as TimeDuration; #[derive(Debug, Eq, PartialEq)] pub enum StatusOrError { Status(StatusCode), ResponseError, } impl fmt::Display for StatusOrError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { StatusOrError::Status(status) => status.fmt(f), StatusOrError::ResponseError => write!(f, "Response error"), } } } #[derive(Debug, Eq, PartialEq)] pub struct MeasuredResponse { pub time: TimeDuration, pub status: StatusOrError, url: Url, } impl Default for MeasuredResponse { fn default() -> MeasuredResponse { MeasuredResponse { time: TimeDuration::zero(), status: StatusOrError::Status(StatusCode::Ok), url: Url::parse("http://example.com").unwrap(), } } } impl MeasuredResponse { pub fn url(&self) -> String { self.url.serialize() } pub fn std_time(&self) -> Duration { self.time.to_std().expect("MeasuredResponse time should never be negative") } pub fn is_success(&self) -> bool { match self.status { StatusOrError::ResponseError => false, StatusOrError::Status(status) => status.is_success(), } } pub fn request(url: &str, timeout: Duration, redirect_count: u8) -> MeasuredResponse { let mut client = Client::new(); client.set_read_timeout(Some(timeout)); client.set_redirect_policy(RedirectPolicy::FollowCount(redirect_count)); let request = client.get(url) .header(Connection::close()); let stop_watch = Stopwatch::start_new(); match request.send() { Err(_) => MeasuredResponse::empty_failure(), Ok(response) => { let duration = TimeDuration::from_std(stop_watch.elapsed()) .expect("Could not read elapsed request time"); MeasuredResponse { status: StatusOrError::Status(response.status), url: response.url.clone(), time: duration, } } } } pub fn empty_failure() -> MeasuredResponse { let mut response = MeasuredResponse::default(); response.status = StatusOrError::ResponseError; response } }
use crate::{types::*, utils::regex::SerializeRegex}; use enum_dispatch::enum_dispatch; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use unicase::UniCase; #[derive(Debug, Serialize, Deserialize)] pub struct Matcher { pub matcher: either::Either<either::Either<String, GraphId>, SerializeRegex>, pub negate: bool, pub case_sensitive: bool, pub empty_always_false: bool, } impl Matcher { pub fn is_slice_match<S: AsRef<str>>( &self, input: &[S], graph: &MatchGraph, case_sensitive: Option<bool>, ) -> bool { input .iter() .any(|x| self.is_match(x.as_ref(), graph, case_sensitive)) } pub fn is_match(&self, input: &str, graph: &MatchGraph, case_sensitive: Option<bool>) -> bool { if input.is_empty() { return if self.empty_always_false { false } else { self.negate }; } let case_sensitive = case_sensitive.unwrap_or(self.case_sensitive); let matches = match &self.matcher { either::Left(string_or_idx) => match string_or_idx { either::Left(string) => { if case_sensitive { string.as_str() == input } else { UniCase::new(string) == UniCase::new(input) } } either::Right(id) => { graph .by_id(*id) .tokens(&graph.tokens) .next() .map_or(false, |token| { if case_sensitive { token.word.text.as_ref() == input } else { UniCase::new(token.word.text.as_ref()) == UniCase::new(input) } }) } }, either::Right(regex) => regex.is_match(input), }; if self.negate { !matches } else { matches } } } #[derive(Debug, Serialize, Deserialize)] pub(crate) struct TextMatcher { pub(crate) matcher: Matcher, pub(crate) set: Option<DefaultHashSet<WordIdInt>>, } impl TextMatcher { pub fn is_match( &self, word_id: &WordId, graph: &MatchGraph, case_sensitive: Option<bool>, ) -> bool { if self.set.is_none() { return self .matcher .is_match(word_id.as_ref(), graph, case_sensitive); } if let Some(id) = word_id.id() { self.set.as_ref().unwrap().contains(id) } else { self.matcher .is_match(word_id.as_ref(), graph, case_sensitive) } } } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct PosMatcher { pub mask: Vec<bool>, } impl PosMatcher { pub fn is_match(&self, pos: &PosId) -> bool { self.mask[pos.id().0 as usize] } } #[derive(Debug, Serialize, Deserialize)] pub struct WordDataMatcher { pub(crate) pos_matcher: Option<PosMatcher>, pub(crate) inflect_matcher: Option<TextMatcher>, } impl WordDataMatcher { pub fn is_match( &self, input: &[WordData], graph: &MatchGraph, case_sensitive: Option<bool>, ) -> bool { input.iter().any(|x| { let pos_matches = self .pos_matcher .as_ref() .map_or(true, |m| m.is_match(&x.pos)); // matching part-of-speech tag is faster than inflection, so check POS first and early exit if it doesn't match if !pos_matches { return false; } let inflect_matches = self .inflect_matcher .as_ref() .map_or(true, |m| m.is_match(&x.lemma, graph, case_sensitive)); inflect_matches }) } } #[derive(Debug, Serialize, Deserialize)] pub struct Quantifier { pub min: usize, pub max: usize, } #[enum_dispatch] pub trait Atomable: Send + Sync { fn is_match(&self, input: &[Token], graph: &MatchGraph, position: usize) -> bool; } #[enum_dispatch(Atomable)] #[derive(Debug, Serialize, Deserialize)] pub enum Atom { ChunkAtom(concrete::ChunkAtom), SpaceBeforeAtom(concrete::SpaceBeforeAtom), TextAtom(concrete::TextAtom), WordDataAtom(concrete::WordDataAtom), TrueAtom, FalseAtom, AndAtom, OrAtom, NotAtom, OffsetAtom, } pub mod concrete { use super::{Atomable, MatchGraph, Matcher, TextMatcher, Token, WordDataMatcher}; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] pub struct TextAtom { pub(crate) matcher: TextMatcher, } impl Atomable for TextAtom { fn is_match(&self, input: &[Token], graph: &MatchGraph, position: usize) -> bool { self.matcher .is_match(&input[position].word.text, graph, None) } } #[derive(Debug, Serialize, Deserialize)] pub struct ChunkAtom { pub(crate) matcher: Matcher, } impl Atomable for ChunkAtom { fn is_match(&self, input: &[Token], graph: &MatchGraph, position: usize) -> bool { self.matcher .is_slice_match(&input[position].chunks, graph, None) } } #[derive(Debug, Serialize, Deserialize)] pub struct SpaceBeforeAtom { pub(crate) value: bool, } impl Atomable for SpaceBeforeAtom { fn is_match(&self, input: &[Token], _graph: &MatchGraph, position: usize) -> bool { input[position].has_space_before == self.value } } #[derive(Debug, Serialize, Deserialize)] pub struct WordDataAtom { pub(crate) matcher: WordDataMatcher, pub(crate) case_sensitive: bool, } impl Atomable for WordDataAtom { fn is_match(&self, input: &[Token], graph: &MatchGraph, position: usize) -> bool { let tags = &input[position].word.tags; self.matcher .is_match(&tags, graph, Some(self.case_sensitive)) } } } #[derive(Debug, Serialize, Deserialize, Default)] pub struct TrueAtom {} impl Atomable for TrueAtom { fn is_match(&self, _input: &[Token], _graph: &MatchGraph, _position: usize) -> bool { true } } #[derive(Debug, Serialize, Deserialize, Default)] pub struct FalseAtom {} impl Atomable for FalseAtom { fn is_match(&self, _input: &[Token], _graph: &MatchGraph, _position: usize) -> bool { false } } #[derive(Debug, Serialize, Deserialize)] pub struct AndAtom { pub(crate) atoms: Vec<Atom>, } impl Atomable for AndAtom { fn is_match(&self, input: &[Token], graph: &MatchGraph, position: usize) -> bool { self.atoms .iter() .all(|x| x.is_match(input, graph, position)) } } #[derive(Debug, Serialize, Deserialize)] pub struct OrAtom { pub(crate) atoms: Vec<Atom>, } impl Atomable for OrAtom { fn is_match(&self, input: &[Token], graph: &MatchGraph, position: usize) -> bool { self.atoms .iter() .any(|x| x.is_match(input, graph, position)) } } #[derive(Debug, Serialize, Deserialize)] pub struct NotAtom { pub(crate) atom: Box<Atom>, } impl Atomable for NotAtom { fn is_match(&self, input: &[Token], graph: &MatchGraph, position: usize) -> bool { !self.atom.is_match(input, graph, position) } } #[derive(Debug, Serialize, Deserialize)] pub struct OffsetAtom { pub(crate) atom: Box<Atom>, pub(crate) offset: isize, } impl Atomable for OffsetAtom { fn is_match(&self, input: &[Token], graph: &MatchGraph, position: usize) -> bool { let new_position = position as isize + self.offset; if new_position < 0 || (new_position as usize) >= input.len() { false } else { self.atom.is_match(input, graph, new_position as usize) } } } #[derive(Debug, Default, Clone)] pub struct Group { pub char_span: (usize, usize), } impl Group { pub fn new(char_span: (usize, usize)) -> Self { Group { char_span } } pub fn tokens<'a, 't>( &'a self, tokens: &'t [Token<'t>], ) -> impl DoubleEndedIterator<Item = &'t Token<'t>> { let start = self.char_span.0; let end = self.char_span.1; tokens.iter().filter(move |x| { x.char_span.1 > x.char_span.0 // special tokens with zero range (e. g. SENT_START) can not be part of groups && x.char_span.0 >= start && x.char_span.1 <= end }) } pub fn text<'a>(&self, text: &'a str) -> &'a str { if self.char_span.0 >= self.char_span.1 { return ""; } let mut char_indices: Vec<_> = text.char_indices().map(|(i, _)| i).collect(); char_indices.push(text.len()); &text[char_indices[self.char_span.0]..char_indices[self.char_span.1]] } } #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] #[serde(transparent)] pub struct GraphId(pub usize); impl GraphId { /// Returns an iterator from the lower bound (inclusive) to the upper bound (inclusive). /// Important: this assumes both ids index into the same graph, otherwise the generated ids /// might not be valid! pub fn range(lower: &GraphId, upper: &GraphId) -> impl DoubleEndedIterator<Item = GraphId> { (lower.0..upper.0 + 1).map(GraphId) } } #[derive(Debug, Clone)] pub struct MatchGraph<'t> { groups: Vec<Group>, id_to_idx: &'t DefaultHashMap<GraphId, usize>, tokens: &'t [Token<'t>], } lazy_static! { static ref EMPTY_MAP: DefaultHashMap<GraphId, usize> = DefaultHashMap::default(); } impl<'t> Default for MatchGraph<'t> { fn default() -> Self { MatchGraph { groups: Vec::new(), id_to_idx: &(*EMPTY_MAP), tokens: &[], } } } impl<'t> MatchGraph<'t> { pub fn new( groups: Vec<Group>, id_to_idx: &'t DefaultHashMap<GraphId, usize>, tokens: &'t [Token<'t>], ) -> Self { MatchGraph { groups, id_to_idx, tokens, } } pub fn by_index(&self, index: usize) -> &Group { &self.groups[index] } pub fn by_id(&self, id: GraphId) -> &Group { &self.groups[self.get_index(id)] } pub fn get_index(&self, id: GraphId) -> usize { *self .id_to_idx .get(&id) .expect("only valid graph indices exist") } pub fn groups(&self) -> &[Group] { &self.groups[..] } pub fn tokens(&self) -> &[Token<'t>] { &self.tokens[..] } pub fn fill_empty(&mut self) { let mut start = self .groups .iter() .find_map(|x| x.tokens(&self.tokens).next().map(|token| token.char_span.0)) .expect("graph must contain at least one token"); let mut end = self .groups .iter() .rev() .find_map(|x| { x.tokens(&self.tokens) .next_back() .map(|token| token.char_span.1) }) .expect("graph must contain at least one token"); let group_tokens: Vec<_> = self .groups .iter() .map(|x| x.tokens(&self.tokens).collect::<Vec<_>>()) .collect::<Vec<_>>(); for (group, tokens) in self.groups.iter_mut().zip(group_tokens.iter()) { if !tokens.is_empty() { group.char_span.0 = tokens[0].char_span.0; group.char_span.1 = tokens[tokens.len() - 1].char_span.1; start = tokens[tokens.len() - 1].char_span.1; } else { group.char_span.1 = start; } } for (group, tokens) in self.groups.iter_mut().zip(group_tokens.iter()).rev() { if !tokens.is_empty() { end = tokens[0].char_span.0; } else { group.char_span.0 = end; } } } } #[derive(Serialize, Deserialize, Debug)] pub struct Part { pub atom: Atom, pub quantifier: Quantifier, pub greedy: bool, pub visible: bool, pub unify: Option<bool>, } #[derive(Serialize, Deserialize, Debug)] pub struct Composition { pub(crate) parts: Vec<Part>, pub(crate) id_to_idx: DefaultHashMap<GraphId, usize>, pub(crate) can_stop_mask: Vec<bool>, } impl Composition { fn next_can_match( &self, tokens: &[Token], graph: &MatchGraph, position: usize, index: usize, ) -> bool { let next_required_pos = match self.parts[index + 1..] .iter() .position(|x| x.quantifier.min > 0) { Some(pos) => index + 1 + pos + 1, None => self.parts.len(), }; self.parts[index + 1..next_required_pos] .iter() .any(|x| x.atom.is_match(tokens, graph, position)) } fn apply_recursive<'t>( &'t self, tokens: &'t [Token<'t>], mut position: usize, mut cur_atom_idx: usize, mut graph: MatchGraph<'t>, ) -> Option<MatchGraph<'t>> { let mut cur_count = 0; let is_match = loop { if cur_atom_idx >= self.parts.len() { break true; } let part = &self.parts[cur_atom_idx]; if cur_count >= part.quantifier.max { cur_atom_idx += 1; cur_count = 0; if cur_atom_idx >= self.parts.len() { break false; } continue; } if position >= tokens.len() { break false; } if cur_count >= part.quantifier.min && cur_atom_idx + 1 < self.parts.len() { if !part.greedy && self.next_can_match(tokens, &graph, position, cur_atom_idx) { cur_atom_idx += 1; cur_count = 0; continue; } if part.greedy { if let Some(graph) = self.apply_recursive(tokens, position, cur_atom_idx + 1, graph.clone()) { return Some(graph); } } } if part.atom.is_match(tokens, &graph, position) { let mut group = &mut graph.groups[cur_atom_idx + 1]; // set the group beginning if the char end was zero (i. e. the group was empty) if group.char_span.1 == 0 { group.char_span.0 = tokens[position].char_span.0; } group.char_span.1 = tokens[position].char_span.1; position += 1; cur_count += 1; } else { break false; } }; // edge case if the last atom is quantified and the minimum has been exceeded // TODO to avoid further such undetected edge cases: revisit the entire composition logic if cur_atom_idx < self.parts.len() && cur_count >= self.parts[cur_atom_idx].quantifier.min { cur_atom_idx += 1; } if is_match || cur_atom_idx == self.parts.len() || self.can_stop_mask[cur_atom_idx] { graph.fill_empty(); Some(graph) } else { None } } pub fn apply<'t>(&'t self, tokens: &'t [Token<'t>], start: usize) -> Option<MatchGraph<'t>> { // this path is extremely hot so more optimizations are done // the first matcher can never rely on the match graph, so we use an empty default graph for the first match // then allocate a new graph if the first matcher matched lazy_static! { static ref DEFAULT_GRAPH: MatchGraph<'static> = MatchGraph::default(); }; if self.parts[0].quantifier.min > 0 && !self.parts[0].atom.is_match(tokens, &DEFAULT_GRAPH, start) { return None; } let position = start; let graph = MatchGraph::new( vec![Group::default(); self.parts.len() + 1], &self.id_to_idx, tokens, ); self.apply_recursive(tokens, position, 0, graph) } }
use crate::schema::u_user; /// User flag pub enum UserFlag { /// 是否启用 Enabled = 1, /// 是否激活 Activated = 2, /// 是否为超级用户 SuperUser = 4, } #[derive(Queryable, Insertable, AsChangeset, Debug, Clone, Serialize, Deserialize)] #[table_name = "u_user"] #[primary_key("id")] #[changeset_for(u_users)] pub struct User { pub id: i32, pub user: String, pub name: String, pub pwd: String, pub flag: i16, pub email: String, pub create_time: i32, } #[derive(Insertable, AsChangeset)] #[table_name = "u_user"] pub struct NewUser { pub user: String, pub name: String, pub pwd: String, pub flag: i16, pub email: String, pub create_time: i32, } impl From<&User> for NewUser { fn from(src: &User) -> Self { Self { user: src.user.to_owned(), name: src.name.to_owned(), pwd: src.pwd.to_owned(), flag: src.flag, email: src.email.to_owned(), create_time: src.create_time, } } }
use std::{ borrow::Cow, collections::{hash_map::RandomState, HashMap}, hash::{BuildHasher, Hash}, marker::PhantomData, }; /// Factory for creating cache storage. pub trait CacheFactory: Send + Sync + 'static { /// Create a cache storage. /// /// TODO: When GAT is stable, this memory allocation can be optimized away. fn create<K, V>(&self) -> Box<dyn CacheStorage<Key = K, Value = V>> where K: Send + Sync + Clone + Eq + Hash + 'static, V: Send + Sync + Clone + 'static; } /// Cache storage for [DataLoader](crate::dataloader::DataLoader). pub trait CacheStorage: Send + Sync + 'static { /// The key type of the record. type Key: Send + Sync + Clone + Eq + Hash + 'static; /// The value type of the record. type Value: Send + Sync + Clone + 'static; /// Returns a reference to the value of the key in the cache or None if it /// is not present in the cache. fn get(&mut self, key: &Self::Key) -> Option<&Self::Value>; /// Puts a key-value pair into the cache. If the key already exists in the /// cache, then it updates the key's value. fn insert(&mut self, key: Cow<'_, Self::Key>, val: Cow<'_, Self::Value>); /// Removes the value corresponding to the key from the cache. fn remove(&mut self, key: &Self::Key); /// Clears the cache, removing all key-value pairs. fn clear(&mut self); } /// No cache. pub struct NoCache; impl CacheFactory for NoCache { fn create<K, V>(&self) -> Box<dyn CacheStorage<Key = K, Value = V>> where K: Send + Sync + Clone + Eq + Hash + 'static, V: Send + Sync + Clone + 'static, { Box::new(NoCacheImpl { _mark1: PhantomData, _mark2: PhantomData, }) } } struct NoCacheImpl<K, V> { _mark1: PhantomData<K>, _mark2: PhantomData<V>, } impl<K, V> CacheStorage for NoCacheImpl<K, V> where K: Send + Sync + Clone + Eq + Hash + 'static, V: Send + Sync + Clone + 'static, { type Key = K; type Value = V; #[inline] fn get(&mut self, _key: &K) -> Option<&V> { None } #[inline] fn insert(&mut self, _key: Cow<'_, Self::Key>, _val: Cow<'_, Self::Value>) {} #[inline] fn remove(&mut self, _key: &K) {} #[inline] fn clear(&mut self) {} } /// [std::collections::HashMap] cache. pub struct HashMapCache<S = RandomState> { _mark: PhantomData<S>, } impl<S: Send + Sync + BuildHasher + Default + 'static> HashMapCache<S> { /// Use specified `S: BuildHasher` to create a `HashMap` cache. pub fn new() -> Self { Self { _mark: PhantomData } } } impl Default for HashMapCache<RandomState> { fn default() -> Self { Self { _mark: PhantomData } } } impl<S: Send + Sync + BuildHasher + Default + 'static> CacheFactory for HashMapCache<S> { fn create<K, V>(&self) -> Box<dyn CacheStorage<Key = K, Value = V>> where K: Send + Sync + Clone + Eq + Hash + 'static, V: Send + Sync + Clone + 'static, { Box::new(HashMapCacheImpl::<K, V, S>(HashMap::<K, V, S>::default())) } } struct HashMapCacheImpl<K, V, S>(HashMap<K, V, S>); impl<K, V, S> CacheStorage for HashMapCacheImpl<K, V, S> where K: Send + Sync + Clone + Eq + Hash + 'static, V: Send + Sync + Clone + 'static, S: Send + Sync + BuildHasher + 'static, { type Key = K; type Value = V; #[inline] fn get(&mut self, key: &Self::Key) -> Option<&Self::Value> { self.0.get(key) } #[inline] fn insert(&mut self, key: Cow<'_, Self::Key>, val: Cow<'_, Self::Value>) { self.0.insert(key.into_owned(), val.into_owned()); } #[inline] fn remove(&mut self, key: &Self::Key) { self.0.remove(key); } #[inline] fn clear(&mut self) { self.0.clear(); } } /// LRU cache. pub struct LruCache { cap: usize, } impl LruCache { /// Creates a new LRU Cache that holds at most `cap` items. pub fn new(cap: usize) -> Self { Self { cap } } } impl CacheFactory for LruCache { fn create<K, V>(&self) -> Box<dyn CacheStorage<Key = K, Value = V>> where K: Send + Sync + Clone + Eq + Hash + 'static, V: Send + Sync + Clone + 'static, { Box::new(LruCacheImpl(lru::LruCache::new(self.cap))) } } struct LruCacheImpl<K, V>(lru::LruCache<K, V>); impl<K, V> CacheStorage for LruCacheImpl<K, V> where K: Send + Sync + Clone + Eq + Hash + 'static, V: Send + Sync + Clone + 'static, { type Key = K; type Value = V; #[inline] fn get(&mut self, key: &Self::Key) -> Option<&Self::Value> { self.0.get(key) } #[inline] fn insert(&mut self, key: Cow<'_, Self::Key>, val: Cow<'_, Self::Value>) { self.0.put(key.into_owned(), val.into_owned()); } #[inline] fn remove(&mut self, key: &Self::Key) { self.0.pop(key); } #[inline] fn clear(&mut self) { self.0.clear(); } }
use std::iter::FromIterator; use heck::CamelCase; use proc_macro2::TokenStream; use quote::{format_ident, quote, quote_spanned}; use syn::spanned::Spanned; use crate::{error::Error, util::ProcMacro}; pub struct ProtobufService { ident: syn::Ident, input: syn::ItemImpl, items: Vec<syn::ImplItem>, } struct MethodInfo<'a> { pub name: String, pub param: &'a syn::Ident, pub returns: &'a syn::Ident, pub validators: Vec<TokenStream>, pub is_result: bool, } impl ProtobufService { fn expand_impl_protobuf_service(&self) -> syn::Result<TokenStream> { let Self { ident, items, .. } = self; let name = ident.to_string(); let mut validators = Vec::new(); let mut methods = Vec::new(); for item in items { match item { syn::ImplItem::Method(method) => { let MethodInfo { name, param, returns, validators: method_validators, is_result, .. } = self.decode_impl_method(method)?; validators.extend(method_validators); let is_async = method.sig.asyncness.is_some(); // Validate parameter let param_type_validator_ident = format_ident!("{}_{}_ParamTypeValidator", ident, name); validators.push(quote_spanned!( param.span()=> #[allow(non_camel_case_types)] trait #param_type_validator_ident: awto::protobuf::IntoProtobufMessage {} impl #param_type_validator_ident for #param {} )); // Validate return type let return_type_validator_ident = format_ident!("{}_{}_ReturnTypeValidator", ident, name); validators.push(quote_spanned!( returns.span()=> #[allow(non_camel_case_types)] trait #return_type_validator_ident: awto::protobuf::IntoProtobufMessage {} impl #return_type_validator_ident for #returns {} )); methods.push(quote!( awto::protobuf::ProtobufMethod { is_async: #is_async, name: #name.to_string(), param: <#param as awto::protobuf::IntoProtobufMessage>::protobuf_message(), returns: <#returns as awto::protobuf::IntoProtobufMessage>::protobuf_message(), returns_result: #is_result, } )) } _ => continue, } } Ok(quote!( impl awto::protobuf::IntoProtobufService for #ident { fn protobuf_service() -> awto::protobuf::ProtobufService { awto::protobuf::ProtobufService { methods: vec![ #( #methods, )* ], module_path: module_path!().to_string(), name: #name.to_string(), } } } #( #validators )* )) } fn decode_impl_method<'a>( &'a self, method: &'a syn::ImplItemMethod, ) -> syn::Result<MethodInfo<'a>> { let name = method.sig.ident.to_string().to_camel_case(); let mut validators = Vec::new(); let mut inputs = method.sig.inputs.iter(); let self_param = inputs.next().ok_or_else(|| { syn::Error::new( method.sig.span(), "protobuf methods must take &self and one input", ) })?; if !matches!(self_param, syn::FnArg::Receiver(_)) { return Err(syn::Error::new( self_param.span(), "the first parameter must be &self", )); } let param = match inputs.next().ok_or_else(|| { syn::Error::new( method.sig.span(), "protobuf methods must take &self and one input", ) })? { syn::FnArg::Receiver(r) => { return Err(syn::Error::new( r.span(), "protobuf methods must take &self and one input", )) } syn::FnArg::Typed(pat_type) => match &*pat_type.ty { syn::Type::Path(type_path) => type_path.path.get_ident().ok_or_else(|| { syn::Error::new( method.sig.span(), "protobuf methods may only accept parameters of structs", ) })?, _ => { return Err(syn::Error::new( method.sig.span(), "protobuf methods may only accept parameters of structs", )) } }, }; let mut is_result = false; let returns = match &method.sig.output { syn::ReturnType::Default => { return Err(syn::Error::new( method.sig.output.span(), "protobuf methods must have a return type", )) } syn::ReturnType::Type(_, ty) => { let return_err = || { syn::Error::new_spanned(ty, "protobuf methods must return a struct or Result<T, E> where E: Into<tonic::Status>") }; match &**ty { syn::Type::Path(type_path) => { if let Some(returns) = type_path.path.get_ident() { returns } else { let segment = type_path.path.segments.first().unwrap(); let segment_ident = segment.ident.to_string().replace(' ', ""); if segment_ident != "Result" && segment_ident != "result::Result" && segment_ident != "std::result::Result" || segment.arguments.is_empty() { return Err(return_err()); } is_result = true; match &segment.arguments { syn::PathArguments::AngleBracketed(inner) => { let mut args = inner.args.iter(); let first = args.next().ok_or_else(return_err)?; let second = args.next().ok_or_else(return_err)?; if args.next().is_some() { return Err(return_err()); } let first = match first { syn::GenericArgument::Type(syn::Type::Path(type_path)) => type_path.path.get_ident().ok_or_else(return_err)?, _ => return Err(return_err()), }; let second = match second { syn::GenericArgument::Type(syn::Type::Path(type_path)) => type_path.path.get_ident().ok_or_else(return_err)?, _ => return Err(return_err()), }; let return_type_result_validator_ident = format_ident!("{}_{}_ReturnTypeResultValidator", self.ident, name); validators.push(quote_spanned!( second.span()=> #[allow(non_camel_case_types)] trait #return_type_result_validator_ident: ::std::convert::Into<::tonic::Status> {} impl #return_type_result_validator_ident for #second {} )); first }, syn::PathArguments::None | syn::PathArguments::Parenthesized(_) => { return Err(return_err()); }, } } }, _ => { return Err(syn::Error::new_spanned( ty, "protobuf methods must return a struct or Result<T, E> where E: Into<tonic::Status>", )) } } } }; Ok(MethodInfo { name, param, returns, validators, is_result, }) } } impl ProcMacro for ProtobufService { type Input = syn::ItemImpl; fn new(input: Self::Input) -> Result<Self, Error> { let ident = match &*input.self_ty { syn::Type::Path(type_path) => type_path.path.get_ident().unwrap().clone(), _ => { return Err(Error::Syn(syn::Error::new( input.impl_token.span, "impl must be on a struct", ))) } }; let items = input.items.clone(); Ok(ProtobufService { ident, input, items, }) } fn expand(self) -> syn::Result<TokenStream> { let input = &self.input; let expanded_input = quote!(#input); let expanded_impl_protobuf_service = self.expand_impl_protobuf_service()?; Ok(TokenStream::from_iter([ expanded_input, expanded_impl_protobuf_service, ])) } }
use crate::{ widgets::{pod::WidgetPod, TypedWidget}, Backend, }; pub trait BoxComponent<T, B: Backend>: TypedWidget<T, B> + Sized + 'static {} pub trait Component<T, B: Backend> { fn component(self) -> WidgetPod<T, B>; }
pub mod choice; pub mod history; pub mod strategy; use choice::*; use history::*; use strategy::*; /// Game holds the data for a sequence of encounters between two strategies. pub struct Game { rounds: usize, h1: History, h2: History, } impl Game { pub fn new(rounds: usize) -> Self { Game { rounds: rounds, h1: History::new(rounds), h2: History::new(rounds), } } // play n rounds of PD between the two strategies, accumulate the history // and return the overall score. pub fn play<T, U>(&mut self, s1: &T, s2: &U) -> (u32, u32) where T: Strategy + ?Sized, U: Strategy + ?Sized { let mut score = (0,0); for _n in 0..self.rounds { let cp = ChoicePair(s1.choice(&self.h1), s2.choice(&self.h2)); // print!("{:?}", cp); let res = cp.score(); score = (score.0 + res.0, score.1 + res.1); // println!("{:?}", score); self.h2.push(cp.swap()); self.h1.push(cp); } score } } #[cfg(test)] mod tests { use super::*; #[test] fn test_game() { // create two histories and two strategies let mut game = Game::new(2); let s1 = AlternateTrueFalse; let s2 = TitForTat; let s3 = TitForTat; let score = game.play(&s1, &s2); println!("{:?}", score); let mut game2 = Game::new(2); let score = game2.play(&s2, &s3); println!("{:?}", score); } }
use std::collections::{HashSet}; #[cfg(test)] mod tests { use super::*; #[test] fn basic() { assert_eq!(center_intersect_distance( parse("R8,U5,L5,D3"), parse("U7,R6,D4,L4"), ), 6); assert_eq!(center_intersect_distance( parse("R75,D30,R83,U83,L12,D49,R71,U7,L72"), parse("U62,R66,U55,R34,D71,R55,D58,R83"), ), 159); assert_eq!(center_intersect_distance( parse("R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51"), parse("U98,R91,D20,R16,D67,R40,U7,R15,U6,R7"), ), 135); } #[test] fn big() { let inp: Vec<&str> = include_str!("aoc_003_input.txt") .trim() .split_ascii_whitespace() .collect(); assert_eq!(center_intersect_distance( parse(inp[0]), parse(inp[1]), ), 248); } } #[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)] struct Pos { x: i32, y: i32, } impl Pos { fn origin() -> Self { Self { x: 0, y: 0 } } fn cmd_steps(&mut self, cmd: &Cmd) -> Vec<Pos> { let mut steps = vec![]; let step = match cmd.direction { Dir::Up => Pos { x: 0, y: -1 }, Dir::Down => Pos { x: 0, y: 1 }, Dir::Left => Pos { x: -1, y: 0 }, Dir::Right => Pos { x: 1, y: 0 }, }; for _ in 0..cmd.distance { *self += step; steps.push(*self); } steps } fn man_dist_to_origin(self: &Self) -> i32 { self.x.abs() + self.y.abs() } } impl std::ops::AddAssign for Pos { fn add_assign(&mut self, rhs: Self) { self.x += rhs.x; self.y += rhs.y; } } enum Dir { Up, Down, Left, Right, } struct Cmd { direction: Dir, distance: i32, } fn parse(wire: &str) -> Vec<Cmd> { wire.split(",").map(|cmd: &str| { let c: Vec<char> = cmd.chars().collect(); let distance = (c[1..]).iter().collect::<String>().parse::<u32>().unwrap() as i32; let direction = match c[0] { 'U' => Dir::Up, 'D' => Dir::Down, 'L' => Dir::Left, 'R' => Dir::Right, _ => panic!("Unknown cmd: {}", cmd), }; Cmd { direction, distance, } }).collect() } fn center_intersect_distance(a: Vec<Cmd>, b: Vec<Cmd>) -> i32 { let a = fill(a); let b = fill(b); let intersect = a.intersection(&b); let mut closest = None; for cross in intersect { if closest.is_none() || cross.man_dist_to_origin() < closest.unwrap() { closest = Some(cross.man_dist_to_origin()) } } closest.unwrap() } fn fill(wire: Vec<Cmd>) -> HashSet<Pos> { let mut used = HashSet::new(); let mut pos = Pos::origin(); for line in wire { for step in pos.cmd_steps(&line) { used.insert(step); } } used }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! AccountManager manages the overall state of Fuchsia accounts and personae on //! a Fuchsia device, installation of the AuthProviders that are used to obtain //! authentication tokens for these accounts, and access to TokenManagers for //! these accounts. //! //! The AccountManager is the most powerful interface in the authentication //! system and is intended only for use by the most trusted parts of the system. #![deny(missing_docs)] mod account_event_emitter; mod account_handler_connection; mod account_handler_context; mod account_manager; pub mod inspect; mod stored_account_list; use crate::account_manager::AccountManager; use failure::{Error, ResultExt}; use fidl_fuchsia_auth::AuthProviderConfig; use fuchsia_async as fasync; use fuchsia_component::fuchsia_single_component_package_url; use fuchsia_component::server::ServiceFs; use fuchsia_inspect::Inspector; use futures::StreamExt; use lazy_static::lazy_static; use log::{error, info}; use std::path::PathBuf; use std::sync::Arc; /// This flag (prefixed with `--`) results in a set of hermetic auth providers. const DEV_AUTH_PROVIDERS_FLAG: &str = "dev-auth-providers"; /// Default data directory for the AccountManager. const DATA_DIR: &str = "/data"; lazy_static! { /// (Temporary) Configuration for a fixed set of auth providers used until file-based /// configuration is available. static ref DEFAULT_AUTH_PROVIDER_CONFIG: Vec<AuthProviderConfig> = { vec![AuthProviderConfig { auth_provider_type: "google".to_string(), url: fuchsia_single_component_package_url!("google_auth_provider").to_string(), params: None }] }; /// Configuration for a set of fake auth providers used for testing. static ref DEV_AUTH_PROVIDER_CONFIG: Vec<AuthProviderConfig> = { vec![AuthProviderConfig { auth_provider_type: "dev_auth_provider".to_string(), url: fuchsia_single_component_package_url!("dev_auth_provider") .to_string(), params: None }] }; } fn main() -> Result<(), Error> { // Parse CLI args let mut opts = getopts::Options::new(); opts.optflag( "", DEV_AUTH_PROVIDERS_FLAG, "use dev auth providers instead of the default set, for tests", ); let args: Vec<String> = std::env::args().collect(); let options = opts.parse(args)?; let auth_provider_config: &Vec<_> = if options.opt_present(DEV_AUTH_PROVIDERS_FLAG) { &DEV_AUTH_PROVIDER_CONFIG } else { &DEFAULT_AUTH_PROVIDER_CONFIG }; fuchsia_syslog::init_with_tags(&["auth"]).expect("Can't init logger"); info!("Starting account manager"); let mut fs = ServiceFs::new(); let inspector = Inspector::new(); inspector.export(&mut fs); let mut executor = fasync::Executor::new().context("Error creating executor")?; let account_manager = Arc::new( AccountManager::new(PathBuf::from(DATA_DIR), &auth_provider_config, &inspector).map_err( |e| { error!("Error initializing AccountManager {:?}", e); e }, )?, ); fs.dir("svc").add_fidl_service(move |stream| { let account_manager_clone = Arc::clone(&account_manager); fasync::spawn(async move { account_manager_clone .handle_requests_from_stream(stream) .await .unwrap_or_else(|e| error!("Error handling AccountManager channel {:?}", e)) }); }); fs.take_and_serve_directory_handle()?; executor.run_singlethreaded(fs.collect::<()>()); info!("Stopping account manager"); Ok(()) }
use std::any::Any; use std::ops::{Bound, RangeBounds}; use crate::mutators::integer::{ binary_search_arbitrary_u16, binary_search_arbitrary_u32, binary_search_arbitrary_u64, binary_search_arbitrary_u8, }; use crate::Mutator; const INITIAL_MUTATION_STEP: u64 = 0; macro_rules! impl_int_mutator_constrained { ($name:ident,$name_unsigned:ident, $name_mutator:ident, $name_binary_arbitrary_function: ident) => { pub struct $name_mutator { start_range: $name, len_range: $name_unsigned, search_space_complexity: f64, rng: fastrand::Rng, } impl $name_mutator { #[no_coverage] pub fn new<RB: RangeBounds<$name>>(range: RB) -> Self { let start = match range.start_bound() { Bound::Included(b) => *b, Bound::Excluded(b) => { assert_ne!(*b, <$name>::MAX); *b + 1 } Bound::Unbounded => <$name>::MIN, }; let end = match range.end_bound() { Bound::Included(b) => *b, Bound::Excluded(b) => { assert_ne!(*b, <$name>::MIN); *b - 1 } Bound::Unbounded => <$name>::MAX, }; if !(start <= end) { panic!( "You have provided a character range where the value of the start of the range \ is larger than the end of the range!\nRange start: {:#?}\nRange end: {:#?}", range.start_bound(), range.end_bound() ) } let length = end.wrapping_sub(start); Self { start_range: start, len_range: end.wrapping_sub(start) as $name_unsigned, search_space_complexity: super::size_to_cplxity(length as usize), rng: fastrand::Rng::default(), } } } impl Mutator<$name> for $name_mutator { #[doc(hidden)] type Cache = (); #[doc(hidden)] type MutationStep = u64; // mutation step #[doc(hidden)] type ArbitraryStep = u64; #[doc(hidden)] type UnmutateToken = $name; // old value #[doc(hidden)] #[no_coverage] fn initialize(&self) {} #[doc(hidden)] #[no_coverage] fn default_arbitrary_step(&self) -> Self::ArbitraryStep { 0 } #[doc(hidden)] #[no_coverage] fn is_valid(&self, value: &$name) -> bool { (self.start_range..=self.start_range.wrapping_add(self.len_range as _)).contains(value) } #[doc(hidden)] #[no_coverage] fn validate_value(&self, value: &$name) -> Option<Self::Cache> { if (self.start_range..=self.start_range.wrapping_add(self.len_range as _)).contains(value) { Some(()) } else { None } } #[doc(hidden)] #[no_coverage] fn default_mutation_step(&self, _value: &$name, _cache: &Self::Cache) -> Self::MutationStep { INITIAL_MUTATION_STEP } #[doc(hidden)] #[no_coverage] fn global_search_space_complexity(&self) -> f64 { self.search_space_complexity } #[doc(hidden)] #[no_coverage] fn max_complexity(&self) -> f64 { <$name>::BITS as f64 } #[doc(hidden)] #[no_coverage] fn min_complexity(&self) -> f64 { <$name>::BITS as f64 } #[doc(hidden)] #[no_coverage] fn complexity(&self, _value: &$name, _cache: &Self::Cache) -> f64 { <$name>::BITS as f64 } #[doc(hidden)] #[no_coverage] fn ordered_arbitrary(&self, step: &mut Self::ArbitraryStep, max_cplx: f64) -> Option<($name, f64)> { if max_cplx < self.min_complexity() { return None; } if *step > self.len_range as u64 { None } else { let result = $name_binary_arbitrary_function(0, self.len_range, *step); *step = step.wrapping_add(1); Some(( self.start_range.wrapping_add(result as $name), <$name>::BITS as f64, )) } } #[doc(hidden)] #[no_coverage] fn random_arbitrary(&self, _max_cplx: f64) -> ($name, f64) { let value = self .rng .$name(self.start_range..=self.start_range.wrapping_add(self.len_range as $name)); (value, <$name>::BITS as f64) } #[doc(hidden)] #[no_coverage] fn ordered_mutate( &self, value: &mut $name, _cache: &mut Self::Cache, step: &mut Self::MutationStep, _subvalue_provider: &dyn crate::SubValueProvider, max_cplx: f64, ) -> Option<(Self::UnmutateToken, f64)> { if max_cplx < self.min_complexity() { return None; } if *step > self.len_range as u64 { return None; } let token = *value; let result = $name_binary_arbitrary_function(0, self.len_range, *step); *value = self.start_range.wrapping_add(result as $name); *step = step.wrapping_add(1); Some((token, <$name>::BITS as f64)) } #[doc(hidden)] #[no_coverage] fn random_mutate( &self, value: &mut $name, _cache: &mut Self::Cache, _max_cplx: f64, ) -> (Self::UnmutateToken, f64) { ( std::mem::replace( value, self.rng .$name(self.start_range..=self.start_range.wrapping_add(self.len_range as $name)), ), <$name>::BITS as f64, ) } #[doc(hidden)] #[no_coverage] fn unmutate(&self, value: &mut $name, _cache: &mut Self::Cache, t: Self::UnmutateToken) { *value = t; } #[doc(hidden)] #[no_coverage] fn visit_subvalues<'a>( &self, _value: &'a $name, _cache: &'a Self::Cache, _visit: &mut dyn FnMut(&'a dyn Any, f64), ) { } } }; } impl_int_mutator_constrained!(u8, u8, U8WithinRangeMutator, binary_search_arbitrary_u8); impl_int_mutator_constrained!(u16, u16, U16WithinRangeMutator, binary_search_arbitrary_u16); impl_int_mutator_constrained!(u32, u32, U32WithinRangeMutator, binary_search_arbitrary_u32); impl_int_mutator_constrained!(u64, u64, U64WithinRangeMutator, binary_search_arbitrary_u64); impl_int_mutator_constrained!(i8, u8, I8WithinRangeMutator, binary_search_arbitrary_u8); impl_int_mutator_constrained!(i16, u16, I16WithinRangeMutator, binary_search_arbitrary_u16); impl_int_mutator_constrained!(i32, u32, I32WithinRangeMutator, binary_search_arbitrary_u32); impl_int_mutator_constrained!(i64, u64, I64WithinRangeMutator, binary_search_arbitrary_u64); #[cfg(test)] mod tests { use super::U8WithinRangeMutator; use crate::Mutator; #[test] fn test_int_constrained() { let m = U8WithinRangeMutator::new(1..2); assert!(m.is_valid(&1)); assert!(!m.is_valid(&2)); } }
mod lib; use lib::queue::*; fn main() { let mut queue = Queue::<i32>::new(16); queue.add(3); queue.add(2); queue.add(1); let peek = match queue.peek() { Ok(x) => x, Err(_e) => 0, }; println!("peek = {:?}", peek); let res = match queue.remove() { Ok(res) => res, Err(_e) => 0 }; println!("res = {:?}", res); let peek = match queue.peek() { Ok(x) => x, Err(_e) => 0, }; println!("peek = {:?}", peek); let res = match queue.remove() { Ok(res) => res, Err(_e) => 0 }; println!("res = {:?}", res); let peek = match queue.peek() { Ok(x) => x, Err(_e) => 0, }; println!("peek = {:?}", peek); let res = match queue.remove() { Ok(res) => res, Err(_e) => 0 }; println!("res = {:?}", res); }
fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let n: usize = rd.get(); let q: usize = rd.get(); let edges: Vec<(usize, usize)> = (0..(n - 1)) .map(|_| { let a: usize = rd.get(); let b: usize = rd.get(); (a - 1, b - 1) }) .collect(); let queries: Vec<(usize, usize, usize)> = (0..q) .map(|_| { let u: usize = rd.get(); let v: usize = rd.get(); let c: usize = rd.get(); (u - 1, v - 1, c) }) .collect(); let mut top: Vec<usize> = (0..n).collect(); let lca = LowestCommonAncestor::from_edges(n, &edges); let par = lca.par.clone(); let dep = lca.dep.clone(); let mut color = vec![0; n]; color[0] = std::usize::MAX; for &(u, v, c) in queries.iter().rev() { let mut fill = |x: usize, y: usize, c: usize| { let mut x = x; loop { let mut history = vec![x]; while x != top[x] { x = top[x]; history.push(x); } history.into_iter().for_each(|xx| { top[xx] = x; }); if dep[x] <= dep[y] { break; } if x != 0 { assert_eq!(color[x], 0); color[x] = c; let p = par[x][0].unwrap(); top[x] = top[p]; x = p; } } }; let w = lca.get(u, v); fill(u, w, c); fill(v, w, c); } use std::collections::HashMap; let mut edges_map = HashMap::new(); for (&(a, b), i) in edges.iter().zip(0..(n - 1)) { edges_map.insert((a, b), i); edges_map.insert((b, a), i); } let mut ans = vec![0; n - 1]; for i in 1..n { let p = par[i][0].unwrap(); let &idx = edges_map.get(&(i, p)).unwrap(); ans[idx] = color[i]; } ans.into_iter().for_each(|ans| println!("{}", ans)); } pub struct LowestCommonAncestor { par: Vec<Vec<Option<usize>>>, dep: Vec<usize>, lg_n: usize, } impl LowestCommonAncestor { pub fn from_edges(n: usize, edges: &[(usize, usize)]) -> Self { let mut g = vec![vec![]; n]; for &(u, v) in edges { g[u].push(v); g[v].push(u); } Self::from_adj_list(&g) } pub fn from_adj_list(g: &[Vec<usize>]) -> Self { fn dfs( i: usize, p: Option<usize>, g: &[Vec<usize>], par: &mut [Vec<Option<usize>>], dep: &mut [usize], ) { par[i][0] = p; for &j in &g[i] { match p { Some(p) if p == j => {} _ => { dep[j] = dep[i] + 1; dfs(j, Some(i), g, par, dep); } } } } let log2 = |k| { let mut exp: usize = 1; let mut m = 1; loop { if m >= k { break exp; } exp += 1; m *= 2; } }; let n = g.len(); let lg_n = log2(n) + 1; let mut par = vec![vec![None; lg_n]; n]; let mut dep = vec![0; n]; dfs(0, None, &g, &mut par, &mut dep); for j in 1..lg_n { for v in 0..n { if let Some(p) = par[v][j - 1] { par[v][j] = par[p][j - 1]; } } } Self { par, dep, lg_n } } pub fn get(&self, u: usize, v: usize) -> usize { let (mut u, mut v) = if self.dep[u] >= self.dep[v] { (u, v) } else { (v, u) }; for i in 0..self.lg_n { if (self.dep[u] - self.dep[v]) >> i & 1 == 1 { u = self.par[u][i].unwrap(); } } if u == v { return u; } for i in (0..self.lg_n).rev() { if self.par[u][i] != self.par[v][i] { u = self.par[u][i].unwrap(); v = self.par[v][i].unwrap(); } } self.par[u][0].unwrap() } } pub struct ProconReader<R> { r: R, line: String, i: usize, } impl<R: std::io::BufRead> ProconReader<R> { pub fn new(reader: R) -> Self { Self { r: reader, line: String::new(), i: 0, } } pub fn get<T>(&mut self) -> T where T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug, { self.skip_blanks(); assert!(self.i < self.line.len()); assert_ne!(&self.line[self.i..=self.i], " "); let line = &self.line[self.i..]; let end = line.find(' ').unwrap_or(line.len()); let s = &line[..end]; self.i += end; s.parse() .unwrap_or_else(|_| panic!("parse error `{}`", self.line)) } fn skip_blanks(&mut self) { loop { let start = self.line[self.i..].find(|ch| ch != ' '); match start { Some(j) => { self.i += j; break; } None => { self.line.clear(); self.i = 0; let num_bytes = self.r.read_line(&mut self.line).unwrap(); assert!(num_bytes > 0, "reached EOF :("); self.line = self.line.trim_end_matches(&['\r', '\n'][..]).to_string(); } } } } pub fn get_vec<T>(&mut self, n: usize) -> Vec<T> where T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug, { (0..n).map(|_| self.get()).collect() } }
#![feature(test, plugin, decl_macro)] #![plugin(rocket_codegen)] extern crate rocket; extern crate rocket_contrib; extern crate rust_embed; use std::path::PathBuf; use std::ffi::OsStr; use std::io::Cursor; use rocket::response; use rocket::http::{ContentType, Status}; use rocket::State; use rust_embed::*; #[get("/")] fn index<'r>(asset: State<Asset>) -> response::Result<'r> { asset("index.html".to_owned()).map_or_else( || Err(Status::NotFound), |d| { response::Response::build() .header(ContentType::HTML) .sized_body(Cursor::new(d)) .ok() }, ) } #[get("/dist/<file..>")] fn dist<'r>(asset: State<Asset>, file: PathBuf) -> response::Result<'r> { let filename = file.display().to_string(); let ext = file.as_path().extension().and_then(OsStr::to_str).expect("Could not get file extension"); let content_type = ContentType::from_extension(ext).expect("Could not get file content type"); asset(filename.clone()).map_or_else( || Err(Status::NotFound), |d| { response::Response::build() .header(content_type) .sized_body(Cursor::new(d)) .ok() }, ) } fn main() { let asset = embed!("examples/public/".to_owned()); rocket::ignite() .manage(asset) .mount("/", routes![index, dist]).launch(); }
use ggez::graphics::spritebatch::SpriteBatch; use ggez::graphics::{Color, DrawMode, DrawParam, Drawable, Mesh, Point2, Rect}; use ggez::{Context, GameResult}; use grid; use hexadventure::prelude::*; use hexadventure::world::mob; pub const WIDTH: u32 = 24; pub struct Sidebar {} impl Sidebar { pub fn new() -> Self { Sidebar {} } pub fn draw( &self, ctx: &mut Context, dest: Point2, world: &World, spritebatch: &mut SpriteBatch, ) -> GameResult<()> { let width = WIDTH as f32 * 9.0; let height = grid::HEIGHT as f32 * 16.0; let background = [ Point2::new(0.0, 0.0), Point2::new(width, 0.0), Point2::new(width, height), Point2::new(0.0, height), ]; let background = Mesh::new_polygon(ctx, DrawMode::Fill, &background)?; background.draw_ex( ctx, DrawParam { dest, color: Some(Color::from_rgb(45, 45, 45)), ..Default::default() }, )?; draw_str( &format!("Health: {}", world.player.health), spritebatch, Point2::new(dest.x + 18.0, dest.y + 16.0), )?; draw_str( &format!("Guard: {}", world.player.guard), spritebatch, Point2::new(dest.x + 18.0, dest.y + 32.0), )?; let mut i = 0; mob::for_each(world, |mob_id| { let mob = &world[mob_id]; draw_str( &format!("Health: {}", mob.health), spritebatch, Point2::new(dest.x + 18.0, dest.y + 48.0 + 32.0 * i as f32), ); draw_str( &format!("Guard: {}", mob.guard), spritebatch, Point2::new(dest.x + 18.0, dest.y + 64.0 + 32.0 * i as f32), ); i += 1; }); // for (index, mob) in game.mobs.npcs.iter().enumerate() { // draw_str(&format!("Guard: {}", mob.guard), spritebatch, Point2::new(dest.x + 18.0, dest.y + 32.0 + 16.0 * index as f32))?; // } Ok(()) } } fn draw_str(string: &str, spritebatch: &mut SpriteBatch, dest: Point2) -> GameResult<()> { for (index, character) in string.bytes().enumerate() { spritebatch.add(DrawParam { src: char_src(character), dest: Point2::new(dest.x + index as f32 * 9.0, dest.y), color: None, ..Default::default() }); } Ok(()) } fn char_src(character: u8) -> Rect { let (x, y) = match character { x @ 32...63 => (x - 32, 0), x @ 64...95 => (x - 64, 1), x @ 96...127 => (x - 96, 2), _ => return Rect::new(0.0, 0.0, 0.0, 0.0), }; let width = 288.0; let height = 288.0; Rect::new( x as f32 * 9.0 / width, y as f32 * 16.0 / height, 9.0 / width, 16.0 / height, ) }
//! Framing for the TNC control protocol //! use std::string::String; use bytes::{Buf, BytesMut}; use futures_codec::{Decoder, Encoder}; use crate::protocol::response::Response; /// Frames and sends TNC control messages pub struct TncControlFraming {} impl TncControlFraming { /// New TNC control message framer pub fn new() -> TncControlFraming { TncControlFraming {} } } impl Encoder for TncControlFraming { type Item = String; type Error = std::io::Error; fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> { dst.extend_from_slice(item.as_bytes()); Ok(()) } } impl Decoder for TncControlFraming { type Item = Response; type Error = std::io::Error; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { // parse the head of src let res = Response::parse(src.as_ref()); // drop parsed characters from the buffer let _ = src.advance(res.0); match &res.1 { Some(ref resp) => trace!("Control received: {:?}", resp), _ => (), } Ok(res.1) } } #[cfg(test)] mod test { use super::*; use std::str; use futures::executor; use futures::io::Cursor; use futures::prelude::*; use futures_codec::Framed; use crate::protocol::response::{Event, Response}; #[test] fn test_encode_decode() { let words = b"PENDING\rCANCELPENDING\r".to_vec(); let curs = Cursor::new(words); let mut framer = Framed::new(curs, TncControlFraming::new()); executor::block_on(async { let e1 = framer.next().await; assert_eq!(Response::Event(Event::PENDING), e1.unwrap().unwrap()); let e2 = framer.next().await; assert_eq!(Response::Event(Event::CANCELPENDING), e2.unwrap().unwrap()); let e3 = framer.next().await; assert!(e3.is_none()); }); let curs = Cursor::new(vec![0u8; 24]); let mut framer = Framed::new(curs, TncControlFraming::new()); executor::block_on(async { framer.send("MYCALL W1AW\r".to_owned()).await.unwrap(); framer.send("LISTEN TRUE\r".to_owned()).await.unwrap(); }); let (curs, _) = framer.release(); assert_eq!( "MYCALL W1AW\rLISTEN TRUE\r", str::from_utf8(curs.into_inner().as_ref()).unwrap() ); } }
#![allow(dead_code)] fn main() { #[cfg(windows)] win_link_libs(); } fn win_link_libs() { println!("cargo:rustc-link-lib=ws2_32"); println!("cargo:rustc-link-lib=netapi32"); println!("cargo:rustc-link-lib=version"); }
mod attributes; pub use attributes::*; mod properties; pub use properties::*; mod tags; pub use tags::*; /// An HTML element. #[derive(Clone)] pub struct El { pub name: String, pub is_text: bool, pub paired: bool, pub attributes: Vec<Attr>, pub style: Vec<Prop>, pub content: Vec<El>, } impl El { /// Creates a new element that displays its name as text and nothing else /// when formatted. This is useful for making innerHTML something other /// than a tag, such as inside the <style> or <script> tags. pub fn text<N: Into<String>>(text: N) -> Self { El { is_text: true, paired: false, name: text.into(), attributes: vec![], style: vec![], content: vec![], } } /// Takes a slice of Attr as input and pushes each member onto .attributes vec. pub fn attributes(mut self, values: &[Attr]) -> Self { for val in values { self.attributes.push(val.clone()); } self } /// Takes a slice of Prop as input and pushes each member onto .style vec. pub fn style(mut self, values: &[Prop]) -> Self { for val in values { self.style.push(val.clone()); } self } /// Takes a slice of El and pushes each element onto .content. pub fn content(mut self, values: &[El]) -> Self { for val in values { self.content.push(val.clone()); } self } /// Allows for finding a child element by its id attribute. pub fn id_find(&mut self, id: &str) -> Option<&mut El> { for attr in self.attributes.iter() { if let Attr::Id(val) = attr { if *val == *id { return Some(self); } } } if !self.is_text && self.paired { for child in self.content.iter_mut() { let find = child.id_find(id); match find { Some(_) => { return find; }, None => (), } } } None } }
// Copyright 2018 Grove Enterprises LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. //! Data sources use std::fs::File; use std::rc::Rc; use std::sync::Arc; use arrow::csv; use arrow::datatypes::Schema; use arrow::record_batch::RecordBatch; use super::error::Result; pub trait DataSource { fn schema(&self) -> &Arc<Schema>; fn next(&mut self) -> Result<Option<RecordBatch>>; } /// CSV data source pub struct CsvDataSource { schema: Arc<Schema>, reader: csv::Reader, } impl CsvDataSource { pub fn new(filename: &str, schema: Arc<Schema>, batch_size: usize) -> Self { let file = File::open(filename).unwrap(); let reader = csv::Reader::new(file, schema.clone(), true, batch_size, None); Self { schema, reader } } pub fn from_reader(schema: Arc<Schema>, reader: csv::Reader) -> Self { Self { schema, reader } } } impl DataSource for CsvDataSource { fn schema(&self) -> &Arc<Schema> { &self.schema } fn next(&mut self) -> Result<Option<RecordBatch>> { Ok(self.reader.next()?) } } //pub struct DataSourceIterator { // pub ds: Rc<RefCell<DataSource>>, //} // //impl DataSourceIterator { // pub fn new(ds: Rc<RefCell<DataSource>>) -> Self { // DataSourceIterator { ds } // } //} // //impl Iterator for DataSourceIterator { // type Item = Result<Rc<RecordBatch>>; // // fn next(&mut self) -> Option<Self::Item> { // self.ds.borrow_mut().next() // } //} #[derive(Serialize, Deserialize, Clone)] pub enum DataSourceMeta { /// Represents a CSV file with a provided schema CsvFile { filename: String, schema: Rc<Schema>, has_header: bool, projection: Option<Vec<usize>>, }, /// Represents a Parquet file that contains schema information ParquetFile { filename: String, schema: Rc<Schema>, projection: Option<Vec<usize>>, }, }
use core::str::from_utf8; use crate::errors::{Error, RnResult}; /// Convert a byte to a decimal string. /// /// If the buffer is too small, `Error::BadParameter` is returned. pub(crate) fn u8_to_str<S>(val: u8, buf: &mut [u8]) -> RnResult<&str, S> { let chars = match val { 0..=9 => 1, 10..=99 => 2, 100..=255 => 3, }; if buf.len() < chars { return Err(Error::BadParameter); } for i in 0..chars { let pos = chars - i - 1; let modulo = val as usize % (10usize.pow(i as u32 + 1)); let digit = modulo / 10usize.pow(i as u32); let ascii = digit + 48; buf[pos] = ascii as u8; } Ok(from_utf8(&buf[0..chars])?) } /// Trim leading zeroes from a hex string. /// /// Examples: /// /// - "1234" -> "1234" /// - "0123" -> "123" /// /// All-zero values will be returned as a single zero: /// /// - "000" -> "0" /// /// Empty values will remain empty: /// /// - "" -> "" /// /// Non-hex characters will be ignored: /// /// - "zzz" -> "zzz" pub(crate) fn ltrim_hex(val: &str) -> &str { if val.is_empty() { return val; } let trimmed = val.trim_start_matches('0'); if trimmed.is_empty() { "0" } else { trimmed } } pub(crate) fn validate_port<T>(port: u8, err: T) -> Result<(), T> { if port >= 1 && port <= 223 { Ok(()) } else { Err(err) } } #[cfg(test)] mod tests { extern crate std; use super::*; mod u8_to_str { use super::*; #[test] fn all_digits() { let mut buf = [0; 3]; for i in 0..=255 { let string = u8_to_str::<()>(i, &mut buf).unwrap(); assert_eq!(string, &std::format!("{}", i)); } } #[test] fn buf_too_small() { let mut buf1 = [0; 1]; let mut buf2 = [0; 2]; let mut buf3 = [0; 3]; assert!(u8_to_str::<()>(9, &mut buf1).is_ok()); assert_eq!(u8_to_str::<()>(10, &mut buf1), Err(Error::BadParameter)); assert!(u8_to_str::<()>(99, &mut buf2).is_ok()); assert_eq!(u8_to_str::<()>(100, &mut buf2), Err(Error::BadParameter)); assert!(u8_to_str::<()>(255, &mut buf3).is_ok()); assert_eq!(u8_to_str::<()>(255, &mut buf2), Err(Error::BadParameter)); } } mod ltrim_hex { use super::*; #[test] fn no_prefix() { assert_eq!(ltrim_hex("1234"), "1234"); } #[test] fn single_prefix() { assert_eq!(ltrim_hex("0123"), "123"); } #[test] fn multi_prefix() { assert_eq!(ltrim_hex("0001"), "1"); } #[test] fn zero() { assert_eq!(ltrim_hex("0000"), "0"); } #[test] fn empty() { assert_eq!(ltrim_hex(""), ""); } #[test] fn nonhex() { assert_eq!(ltrim_hex("zzz"), "zzz"); } } }
use block_device::BlockDevice; use super::partition::Partition; use collections::vec::*; const PARTITION_TABLE_OFFSET: usize = 0x01BE; pub struct MbrDeviceDriver<'a> { first_partition: Partition<'a>, } impl<'a> MbrDeviceDriver<'a> { pub fn new(block_device: &'a BlockDevice) -> MbrDeviceDriver<'a> { if !(block_device.block_size() >= 512 && block_device.block_size() % 512 == 0) { panic!("512"); } let mbr = block_device.read_blocks(0, 1); let mut first_entry: Vec<u8> = Vec::with_capacity(16); for i in 0..16 { first_entry.push(mbr[PARTITION_TABLE_OFFSET + i]); } let first_partition = Partition::new(block_device, &first_entry); MbrDeviceDriver { first_partition: first_partition } } pub fn get_first_partition(&self) -> &Partition { &self.first_partition } }
pub struct WorkoutPlan { pub id: String, pub name: String, pub start_date: String, pub end_date: String, pub workout_ids: Vec<String>, }
use std::cmp::Ordering; use super::snowflake::ProcessUniqueId; use super::*; /// /// A `Tree` builder that provides more control over how a `Tree` is created. /// pub struct TreeBuilder<T> { root: Option<Node<T>>, node_capacity: usize, swap_capacity: usize, } impl<T> TreeBuilder<T> { /// /// Creates a new `TreeBuilder` with the default settings. /// /// ``` /// use id_tree::TreeBuilder; /// /// let _tree_builder: TreeBuilder<i32> = TreeBuilder::new(); /// ``` /// pub fn new() -> TreeBuilder<T> { TreeBuilder { root: None, node_capacity: 0, swap_capacity: 0, } } /// /// Sets the root `Node` of the `TreeBuilder`. /// /// ``` /// use id_tree::TreeBuilder; /// use id_tree::Node; /// /// let _tree_builder = TreeBuilder::new().with_root(Node::new(1)); /// ``` /// pub fn with_root(mut self, root: Node<T>) -> TreeBuilder<T> { self.root = Some(root); self } /// /// Sets the node_capacity of the `TreeBuilder`. /// /// Since `Tree`s own their `Node`s, they must allocate storage space as `Node`s are inserted. /// Using this setting allows the `Tree` to pre-allocate space for `Node`s ahead of time, so /// that the space allocations don't happen as the `Node`s are inserted. /// /// _Use of this setting is recommended if you know the **maximum number** of `Node`s that your /// `Tree` will **contain** at **any given time**._ /// /// ``` /// use id_tree::TreeBuilder; /// /// let _tree_builder: TreeBuilder<i32> = TreeBuilder::new().with_node_capacity(3); /// ``` /// pub fn with_node_capacity(mut self, node_capacity: usize) -> TreeBuilder<T> { self.node_capacity = node_capacity; self } /// /// Sets the swap_capacity of the `TreeBuilder`. /// /// This is important because `Tree`s attempt to save time by re-using storage space when /// `Node`s are removed (instead of shuffling `Node`s around internally). To do this, the /// `Tree` must store information about the space left behind when a `Node` is removed. Using /// this setting allows the `Tree` to pre-allocate this storage space instead of doing so as /// `Node`s are removed from the `Tree`. /// /// _Use of this setting is recommended if you know the **maximum "net number of /// removals"** that have occurred **at any given time**._ /// /// For example: /// --- /// In **Scenario 1**: /// /// * Add 3 `Node`s, Remove 2 `Node`s, Add 1 `Node`. /// /// The most amount of nodes that have been removed at any given time is **2**. /// /// But in **Scenario 2**: /// /// * Add 3 `Node`s, Remove 2 `Node`s, Add 1 `Node`, Remove 2 `Node`s. /// /// The most amount of nodes that have been removed at any given time is **3**. /// /// ``` /// use id_tree::TreeBuilder; /// /// let _tree_builder: TreeBuilder<i32> = TreeBuilder::new().with_swap_capacity(3); /// ``` /// pub fn with_swap_capacity(mut self, swap_capacity: usize) -> TreeBuilder<T> { self.swap_capacity = swap_capacity; self } /// /// Build a `Tree` based upon the current settings in the `TreeBuilder`. /// /// ``` /// use id_tree::TreeBuilder; /// use id_tree::Tree; /// use id_tree::Node; /// /// let _tree: Tree<i32> = TreeBuilder::new() /// .with_root(Node::new(5)) /// .with_node_capacity(3) /// .with_swap_capacity(2) /// .build(); /// ``` /// pub fn build(mut self) -> Tree<T> { let tree_id = ProcessUniqueId::new(); let mut tree = Tree { id: tree_id, root: None, nodes: Vec::with_capacity(self.node_capacity), free_ids: Vec::with_capacity(self.swap_capacity), }; if self.root.is_some() { let node_id = NodeId { tree_id: tree_id, index: 0, }; tree.nodes.push(self.root.take()); tree.root = Some(node_id); } tree } } /// /// A tree structure consisting of `Node`s. /// /// # Panics /// While it is highly unlikely, any function that takes a `NodeId` _can_ `panic`. This, however, /// should only happen due to improper `NodeId` management within `id_tree` and should have nothing /// to do with the library user's code. /// /// **If this ever happens please report the issue.** `Panic`s are not expected behavior for this /// library, but they can happen due to bugs. /// #[derive(Debug)] pub struct Tree<T> { id: ProcessUniqueId, root: Option<NodeId>, pub(crate) nodes: Vec<Option<Node<T>>>, free_ids: Vec<NodeId>, } impl<T> Tree<T> { /// /// Creates a new `Tree` with default settings (no root `Node` and no space pre-allocation). /// /// ``` /// use id_tree::Tree; /// /// let _tree: Tree<i32> = Tree::new(); /// ``` /// pub fn new() -> Tree<T> { TreeBuilder::new().build() } /// /// Returns the number of elements the tree can hold without reallocating. /// pub fn capacity(&self) -> usize { self.nodes.capacity() } /// /// Returns the maximum height of the `Tree`. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// assert_eq!(0, tree.height()); /// /// let root_id = tree.insert(Node::new(1), AsRoot).unwrap(); /// assert_eq!(1, tree.height()); /// /// tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); /// assert_eq!(2, tree.height()); /// ``` /// pub fn height(&self) -> usize { match self.root { Some(ref id) => self.height_of_node(id), _ => 0, } } fn height_of_node(&self, node: &NodeId) -> usize { let mut h = 0; for n in self.children_ids(node).unwrap() { h = std::cmp::max(h, self.height_of_node(n)); } h + 1 } /// Inserts a new `Node` into the `Tree`. The `InsertBehavior` provided will determine where /// the `Node` is inserted. /// /// Returns a `Result` containing the `NodeId` of the `Node` that was inserted or a /// `NodeIdError` if one occurred. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let root_node = Node::new(1); /// let child_node = Node::new(2); /// /// let mut tree: Tree<i32> = Tree::new(); /// let root_id = tree.insert(root_node, AsRoot).unwrap(); /// /// tree.insert(child_node, UnderNode(&root_id)).unwrap(); /// ``` /// pub fn insert( &mut self, node: Node<T>, behavior: InsertBehavior, ) -> Result<NodeId, NodeIdError> { match behavior { InsertBehavior::UnderNode(parent_id) => { let (is_valid, error) = self.is_valid_node_id(parent_id); if !is_valid { return Err(error.expect( "Tree::insert: Missing an error value but found an \ invalid NodeId.", )); } self.insert_with_parent(node, parent_id) } InsertBehavior::AsRoot => Ok(self.set_root(node)), } } /// /// Sets the root of the `Tree`. /// fn set_root(&mut self, new_root: Node<T>) -> NodeId { let new_root_id = self.insert_new_node(new_root); if let Some(current_root_node_id) = self.root.clone() { self.set_as_parent_and_child(&new_root_id, &current_root_node_id); } self.root = Some(new_root_id.clone()); new_root_id } /// Add a new `Node` to the tree as the child of a `Node` specified by the given `NodeId`. /// fn insert_with_parent( &mut self, child: Node<T>, parent_id: &NodeId, ) -> Result<NodeId, NodeIdError> { let new_child_id = self.insert_new_node(child); self.set_as_parent_and_child(parent_id, &new_child_id); Ok(new_child_id) } /// /// Get an immutable reference to a `Node`. /// /// Returns a `Result` containing the immutable reference or a `NodeIdError` if one occurred. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// let root_id = tree.insert(Node::new(5), AsRoot).unwrap(); /// /// let root_node: &Node<i32> = tree.get(&root_id).unwrap(); /// /// # assert_eq!(root_node.data(), &5); /// ``` /// pub fn get(&self, node_id: &NodeId) -> Result<&Node<T>, NodeIdError> { let (is_valid, error) = self.is_valid_node_id(node_id); if !is_valid { Err(error.expect("Tree::get: Missing an error value on finding an invalid NodeId.")) } else { Ok(self.get_unsafe(node_id)) } } /// /// Get a mutable reference to a `Node`. /// /// Returns a `Result` containing the mutable reference or a `NodeIdError` if one occurred. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// let root_id = tree.insert(Node::new(5), AsRoot).unwrap(); /// /// let root_node: &mut Node<i32> = tree.get_mut(&root_id).unwrap(); /// /// # assert_eq!(root_node.data(), &5); /// ``` /// pub fn get_mut(&mut self, node_id: &NodeId) -> Result<&mut Node<T>, NodeIdError> { let (is_valid, error) = self.is_valid_node_id(node_id); if !is_valid { Err(error.expect("Tree::get_mut: Missing an error value on finding an invalid NodeId.")) } else { Ok(self.get_mut_unsafe(node_id)) } } /// Remove a `Node` from the `Tree`. The `RemoveBehavior` provided determines what happens to /// the removed `Node`'s children. /// /// Returns a `Result` containing the removed `Node` or a `NodeIdError` if one occurred. /// /// **NOTE:** The `Node` that is returned will have its parent and child values cleared to avoid /// providing the caller with extra copies of `NodeId`s should the corresponding `Node`s be /// removed from the `Tree` at a later time. /// /// If the caller needs a copy of the parent or child `NodeId`s, they must `Clone` them before /// this `Node` is removed from the `Tree`. Please see the /// [Potential `NodeId` Issues](struct.NodeId.html#potential-nodeid-issues) section /// of the `NodeId` documentation for more information on the implications of calling `Clone` on /// a `NodeId`. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// use id_tree::RemoveBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); /// /// let child_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); /// let grandchild_id = tree.insert(Node::new(2), UnderNode(&child_id)).unwrap(); /// /// let child = tree.remove_node(child_id, DropChildren).unwrap(); /// /// # assert!(tree.get(&grandchild_id).is_err()); /// # assert_eq!(tree.get(&root_id).unwrap().children().len(), 0); /// # assert_eq!(child.children().len(), 0); /// # assert_eq!(child.parent(), None); /// ``` /// pub fn remove_node( &mut self, node_id: NodeId, behavior: RemoveBehavior, ) -> Result<Node<T>, NodeIdError> { let (is_valid, error) = self.is_valid_node_id(&node_id); if !is_valid { return Err(error.expect( "Tree::remove_node: Missing an error value but found an \ invalid NodeId.", )); } match behavior { RemoveBehavior::DropChildren => self.remove_node_drop_children(node_id), RemoveBehavior::LiftChildren => self.remove_node_lift_children(node_id), RemoveBehavior::OrphanChildren => self.remove_node_orphan_children(node_id), } } /// /// Remove a `Node` from the `Tree` and move its children up one "level" in the `Tree` if /// possible. /// /// In other words, this `Node`'s children will point to its parent as their parent instead of /// this `Node`. In addition, this `Node`'s parent will have this `Node`'s children added as /// its own children. If this `Node` has no parent, then calling this function is the /// equivalent of calling `remove_node_orphan_children`. /// fn remove_node_lift_children(&mut self, node_id: NodeId) -> Result<Node<T>, NodeIdError> { if let Some(parent_id) = self.get_unsafe(&node_id).parent().cloned() { // attach children to parent for child_id in self.get_unsafe(&node_id).children().clone() { self.set_as_parent_and_child(&parent_id, &child_id); } } else { self.clear_parent_of_children(&node_id); } Ok(self.remove_node_internal(node_id)) } /// /// Remove a `Node` from the `Tree` and leave all of its children in the `Tree`. /// fn remove_node_orphan_children(&mut self, node_id: NodeId) -> Result<Node<T>, NodeIdError> { self.clear_parent_of_children(&node_id); Ok(self.remove_node_internal(node_id)) } /// /// Remove a `Node` from the `Tree` including all its children recursively. /// fn remove_node_drop_children(&mut self, node_id: NodeId) -> Result<Node<T>, NodeIdError> { let mut children = self.get_mut_unsafe(&node_id).take_children(); for child in children.drain(..) { try!(self.remove_node_drop_children(child)); } Ok(self.remove_node_internal(node_id)) } /// Moves a `Node` in the `Tree` to a new location based upon the `MoveBehavior` provided. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// use id_tree::MoveBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// /// let root_id = tree.insert(Node::new(1), AsRoot).unwrap(); /// let child_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); /// let grandchild_id = tree.insert(Node::new(3), UnderNode(&child_id)).unwrap(); /// /// tree.move_node(&grandchild_id, ToRoot).unwrap(); /// /// assert_eq!(tree.root_node_id(), Some(&grandchild_id)); /// # assert!(tree.get(&grandchild_id).unwrap().children().contains(&root_id)); /// # assert!(!tree.get(&child_id).unwrap().children().contains(&grandchild_id)); /// ``` /// pub fn move_node( &mut self, node_id: &NodeId, behavior: MoveBehavior, ) -> Result<(), NodeIdError> { let (is_valid, error) = self.is_valid_node_id(node_id); if !is_valid { return Err(error.expect( "Tree::move_node: Missing an error value on finding an \ invalid NodeId.", )); } match behavior { MoveBehavior::ToRoot => self.move_node_to_root(node_id), MoveBehavior::ToParent(parent_id) => { let (is_valid, error) = self.is_valid_node_id(parent_id); if !is_valid { return Err(error.expect( "Tree::move_node: Missing an error value on finding \ an invalid NodeId.", )); } self.move_node_to_parent(node_id, parent_id) } } } /// Moves a `Node` inside a `Tree` to a new parent leaving all children in their place. /// fn move_node_to_parent( &mut self, node_id: &NodeId, parent_id: &NodeId, ) -> Result<(), NodeIdError> { if let Some(subtree_root_id) = self .find_subtree_root_between_ids(parent_id, node_id) .cloned() { // node_id is above parent_id, this is a move "down" the tree. let root = self.root.clone(); if root.as_ref() == Some(node_id) { // we're moving the root down the tree. // also we know the root exists // detach subtree_root from node self.detach_from_parent(node_id, &subtree_root_id); // set subtree_root as Tree root. self.clear_parent(&subtree_root_id); self.root = Some(subtree_root_id); self.set_as_parent_and_child(parent_id, node_id); } else { // we're moving some other node down the tree. if let Some(old_parent) = self.get_unsafe(node_id).parent().cloned() { // detach from old parent self.detach_from_parent(&old_parent, node_id); // connect old parent and subtree root self.set_as_parent_and_child(&old_parent, &subtree_root_id); } else { // node is orphaned, need to set subtree_root's parent to None (same as node's) self.clear_parent(&subtree_root_id); } // detach subtree_root from node self.detach_from_parent(node_id, &subtree_root_id); self.set_as_parent_and_child(parent_id, node_id); } } else { // this is a move "across" or "up" the tree. // detach from old parent if let Some(old_parent) = self.get_unsafe(node_id).parent().cloned() { self.detach_from_parent(&old_parent, node_id); } self.set_as_parent_and_child(parent_id, node_id); } Ok(()) } /// /// Sets a `Node` inside a `Tree` as the new root `Node`, leaving all children in their place. /// fn move_node_to_root(&mut self, node_id: &NodeId) -> Result<(), NodeIdError> { let old_root = self.root.clone(); if let Some(parent_id) = self.get_unsafe(node_id).parent().cloned() { self.detach_from_parent(&parent_id, node_id); } self.clear_parent(node_id); self.root = Some(node_id.clone()); if let Some(old_root) = old_root { try!(self.move_node_to_parent(&old_root, node_id)); } Ok(()) } /// /// Sorts the children of one node, in-place, using compare to compare the nodes /// /// This sort is stable and O(n log n) worst-case but allocates approximately 2 * n where n is /// the length of children /// /// Returns an empty `Result` containing a `NodeIdError` if one occurred. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// /// let root_id = tree.insert(Node::new(100), AsRoot).unwrap(); /// tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); /// tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); /// tree.insert(Node::new(0), UnderNode(&root_id)).unwrap(); /// /// tree.sort_children_by(&root_id, |a, b| a.data().cmp(b.data())).unwrap(); /// /// # for (i, id) in tree.get(&root_id).unwrap().children().iter().enumerate() { /// # assert_eq!(*tree.get(&id).unwrap().data(), i as i32); /// # } /// ``` /// pub fn sort_children_by<F>( &mut self, node_id: &NodeId, mut compare: F, ) -> Result<(), NodeIdError> where F: FnMut(&Node<T>, &Node<T>) -> Ordering, { let (is_valid, error) = self.is_valid_node_id(node_id); if !is_valid { return Err(error.expect( "Tree::sort_children_by: Missing an error value but found an invalid NodeId.", )); } let mut children = self.get_mut_unsafe(node_id).take_children(); children.sort_by(|a, b| compare(self.get_unsafe(a), self.get_unsafe(b))); self.get_mut_unsafe(node_id).set_children(children); Ok(()) } /// /// Sorts the children of one node, in-place, comparing their data /// /// This sort is stable and O(n log n) worst-case but allocates approximately 2 * n where n is /// the length of children /// /// Returns an empty `Result` containing a `NodeIdError` if one occurred. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// /// let root_id = tree.insert(Node::new(100), AsRoot).unwrap(); /// tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); /// tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); /// tree.insert(Node::new(0), UnderNode(&root_id)).unwrap(); /// /// tree.sort_children_by_data(&root_id).unwrap(); /// /// # for (i, id) in tree.get(&root_id).unwrap().children().iter().enumerate() { /// # assert_eq!(*tree.get(&id).unwrap().data(), i as i32); /// # } /// ``` /// pub fn sort_children_by_data(&mut self, node_id: &NodeId) -> Result<(), NodeIdError> where T: Ord, { let (is_valid, error) = self.is_valid_node_id(node_id); if !is_valid { return Err(error.expect( "Tree::sort_children: Missing an error value but found an invalid NodeId.", )); } let mut children = self.get_mut_unsafe(node_id).take_children(); children.sort_by_key(|a| self.get_unsafe(a).data()); self.get_mut_unsafe(node_id).set_children(children); Ok(()) } /// /// Sorts the children of one node, in-place, using f to extract a key by which to order the /// sort by. /// /// This sort is stable and O(n log n) worst-case but allocates approximately 2 * n where n is /// the length of children /// /// Returns an empty `Result` containing a `NodeIdError` if one occurred. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// /// let root_id = tree.insert(Node::new(100), AsRoot).unwrap(); /// tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); /// tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); /// tree.insert(Node::new(0), UnderNode(&root_id)).unwrap(); /// /// tree.sort_children_by_key(&root_id, |x| x.data().clone()).unwrap(); /// /// # for (i, id) in tree.get(&root_id).unwrap().children().iter().enumerate() { /// # assert_eq!(*tree.get(&id).unwrap().data(), i as i32); /// # } /// ``` /// pub fn sort_children_by_key<B, F>( &mut self, node_id: &NodeId, mut f: F, ) -> Result<(), NodeIdError> where B: Ord, F: FnMut(&Node<T>) -> B, { let (is_valid, error) = self.is_valid_node_id(node_id); if !is_valid { return Err(error.expect( "Tree::sort_children_by_key: Missing an error value but found an invalid NodeId.", )); } let mut children = self.get_mut_unsafe(node_id).take_children(); children.sort_by_key(|a| f(self.get_unsafe(a))); self.get_mut_unsafe(node_id).set_children(children); Result::Ok(()) } /// Swap `Node`s in the `Tree` based upon the `SwapBehavior` provided. /// /// Both `NodeId`s are still valid after this process and are not swapped. /// /// This keeps the positions of the `Node`s in their parents' children collection. /// /// Returns an empty `Result` containing a `NodeIdError` if one occurred on either provided /// `NodeId`. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// use id_tree::SwapBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// /// let root_id = tree.insert(Node::new(1), AsRoot).unwrap(); /// /// let first_child_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); /// let second_child_id = tree.insert(Node::new(3), UnderNode(&root_id)).unwrap(); /// let grandchild_id = tree.insert(Node::new(4), UnderNode(&second_child_id)).unwrap(); /// /// tree.swap_nodes(&first_child_id, &grandchild_id, TakeChildren).unwrap(); /// /// assert!(tree.get(&second_child_id).unwrap().children().contains(&first_child_id)); /// assert!(tree.get(&root_id).unwrap().children().contains(&grandchild_id)); /// ``` /// pub fn swap_nodes( &mut self, first_id: &NodeId, second_id: &NodeId, behavior: SwapBehavior, ) -> Result<(), NodeIdError> { let (is_valid, error) = self.is_valid_node_id(first_id); if !is_valid { return Err(error .expect("Tree::swap_nodes: Missing an error value but found an invalid NodeId.")); } let (is_valid, error) = self.is_valid_node_id(second_id); if !is_valid { return Err(error .expect("Tree::swap_nodes: Missing an error value but found an invalid NodeId.")); } match behavior { SwapBehavior::TakeChildren => self.swap_nodes_take_children(first_id, second_id), SwapBehavior::LeaveChildren => self.swap_nodes_leave_children(first_id, second_id), SwapBehavior::ChildrenOnly => self.swap_nodes_children_only(first_id, second_id), } } /// Swaps two `Node`s including their children given their `NodeId`s. /// fn swap_nodes_take_children( &mut self, first_id: &NodeId, second_id: &NodeId, ) -> Result<(), NodeIdError> { let lower_upper_test = self .find_subtree_root_between_ids(first_id, second_id) .map(|_| (first_id, second_id)) .or_else(|| { self.find_subtree_root_between_ids(second_id, first_id) .map(|_| (second_id, first_id)) }); if let Some((lower_id, upper_id)) = lower_upper_test { let upper_parent_id = self.get_unsafe(upper_id).parent().cloned(); let lower_parent_id = { let lower = self.get_mut_unsafe(lower_id); // lower is lower, so it has a parent for sure let lower_parent_id = lower.parent().unwrap().clone(); if upper_parent_id.is_some() { lower.set_parent(upper_parent_id.clone()); } else { lower.set_parent(None); } lower_parent_id }; self.detach_from_parent(&lower_parent_id, lower_id); if upper_parent_id.is_some() { self.get_mut_unsafe(upper_parent_id.as_ref().unwrap()) .replace_child(upper_id.clone(), lower_id.clone()); } else if self.root.as_ref() == Some(upper_id) { self.root = Some(lower_id.clone()); } self.get_mut_unsafe(upper_id) .set_parent(Some(lower_id.clone())); self.get_mut_unsafe(lower_id).add_child(upper_id.clone()); } else { // just across let is_same_parent = self.get_unsafe(first_id).parent() == self.get_unsafe(second_id).parent(); if is_same_parent { let parent_id = self.get_unsafe(first_id).parent().cloned(); if let Some(parent_id) = parent_id { // same parent // get indices let parent = self.get_mut_unsafe(&parent_id); let first_index = parent .children() .iter() .enumerate() .find(|&(_, id)| id == first_id) .unwrap() .0; let second_index = parent .children() .iter() .enumerate() .find(|&(_, id)| id == second_id) .unwrap() .0; parent.children_mut().swap(first_index, second_index); } else { // swapping the root with itself?? } } else { let first_parent_id = self.get_unsafe(first_id).parent().cloned().unwrap(); let second_parent_id = self.get_unsafe(second_id).parent().cloned().unwrap(); // replace parents self.get_mut_unsafe(first_id) .set_parent(Some(second_parent_id.clone())); self.get_mut_unsafe(second_id) .set_parent(Some(first_parent_id.clone())); // change children self.get_mut_unsafe(&first_parent_id) .replace_child(first_id.clone(), second_id.clone()); self.get_mut_unsafe(&second_parent_id) .replace_child(second_id.clone(), first_id.clone()); } } Ok(()) } fn swap_nodes_leave_children( &mut self, first_id: &NodeId, second_id: &NodeId, ) -> Result<(), NodeIdError> { //take care of these nodes' children's parent values self.set_parent_of_children(first_id, Some(second_id.clone())); self.set_parent_of_children(second_id, Some(first_id.clone())); //swap children of these nodes let first_children = self.get_unsafe(first_id).children().clone(); let second_children = self.get_unsafe(second_id).children().clone(); self.get_mut_unsafe(first_id).set_children(second_children); self.get_mut_unsafe(second_id).set_children(first_children); let first_parent = self.get_unsafe(first_id).parent().cloned(); let second_parent = self.get_unsafe(second_id).parent().cloned(); //todo: some of this could probably be abstracted out into a method or two match (first_parent, second_parent) { (Some(ref first_parent_id), Some(ref second_parent_id)) => { let first_index = self .get_unsafe(first_parent_id) .children() .iter() .position(|id| id == first_id) .unwrap(); let second_index = self .get_unsafe(second_parent_id) .children() .iter() .position(|id| id == second_id) .unwrap(); unsafe { let temp = self .get_mut_unsafe(first_parent_id) .children_mut() .get_unchecked_mut(first_index); *temp = second_id.clone(); } unsafe { let temp = self .get_mut_unsafe(second_parent_id) .children_mut() .get_unchecked_mut(second_index); *temp = first_id.clone(); } self.get_mut_unsafe(first_id) .set_parent(Some(second_parent_id.clone())); self.get_mut_unsafe(second_id) .set_parent(Some(first_parent_id.clone())); } (Some(ref first_parent_id), None) => { let first_index = self .get_unsafe(first_parent_id) .children() .iter() .position(|id| id == first_id) .unwrap(); unsafe { let temp = self .get_mut_unsafe(first_parent_id) .children_mut() .get_unchecked_mut(first_index); *temp = second_id.clone(); } self.get_mut_unsafe(first_id).set_parent(None); self.get_mut_unsafe(second_id) .set_parent(Some(first_parent_id.clone())); if let Some(root_id) = self.root_node_id().cloned() { if root_id == second_id.clone() { self.root = Some(first_id.clone()); } } } (None, Some(ref second_parent_id)) => { let second_index = self .get_unsafe(second_parent_id) .children() .iter() .position(|id| id == second_id) .unwrap(); unsafe { let temp = self .get_mut_unsafe(second_parent_id) .children_mut() .get_unchecked_mut(second_index); *temp = first_id.clone(); } self.get_mut_unsafe(first_id) .set_parent(Some(second_parent_id.clone())); self.get_mut_unsafe(second_id).set_parent(None); if let Some(root_id) = self.root_node_id().cloned() { if root_id == first_id.clone() { self.root = Some(second_id.clone()); } } } (None, None) => { if let Some(root_id) = self.root_node_id().cloned() { if root_id == first_id.clone() { self.root = Some(second_id.clone()); } else if root_id == second_id.clone() { self.root = Some(first_id.clone()); } } } } Ok(()) } fn swap_nodes_children_only( &mut self, first_id: &NodeId, second_id: &NodeId, ) -> Result<(), NodeIdError> { let lower_upper_test = self .find_subtree_root_between_ids(first_id, second_id) .map(|_| (first_id, second_id)) .or_else(|| { self.find_subtree_root_between_ids(second_id, first_id) .map(|_| (second_id, first_id)) }); // todo: lots of repetition in here let first_children = self.get_unsafe(first_id).children().clone(); let second_children = self.get_unsafe(second_id).children().clone(); if let Some((lower_id, upper_id)) = lower_upper_test { let lower_parent = self.get_unsafe(lower_id).parent().cloned().unwrap(); let (mut upper_children, lower_children) = if upper_id == first_id { (first_children, second_children) } else { (second_children, first_children) }; for child in &upper_children { self.get_mut_unsafe(child) .set_parent(Some(lower_id.clone())); } for child in &lower_children { self.get_mut_unsafe(child) .set_parent(Some(upper_id.clone())); } if upper_id == &lower_parent { // direct child upper_children.retain(|id| id != lower_id); } //swap children of these nodes self.get_mut_unsafe(upper_id).set_children(lower_children); self.get_mut_unsafe(lower_id).set_children(upper_children); //add lower to upper self.set_as_parent_and_child(upper_id, lower_id); } else { //just across //take care of these nodes' children's parent values for child in &first_children { self.get_mut_unsafe(child) .set_parent(Some(second_id.clone())); } for child in &second_children { self.get_mut_unsafe(child) .set_parent(Some(first_id.clone())); } //swap children of these nodes self.get_mut_unsafe(first_id).set_children(second_children); self.get_mut_unsafe(second_id).set_children(first_children); } Ok(()) } /// /// Returns a `Some` value containing the `NodeId` of the root `Node` if it exists. Otherwise a /// `None` value is returned. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// let root_id = tree.insert(Node::new(5), AsRoot).unwrap(); /// /// assert_eq!(&root_id, tree.root_node_id().unwrap()); /// ``` /// pub fn root_node_id(&self) -> Option<&NodeId> { self.root.as_ref() } /// /// Returns an `Ancestors` iterator (or a `NodeIdError` if one occurred). /// /// Allows iteration over the ancestor `Node`s of a given `NodeId` directly instead of having /// to call `tree.get(...)` with a `NodeId` each time. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); /// let node_1 = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); /// /// let mut ancestors = tree.ancestors(&node_1).unwrap(); /// /// assert_eq!(ancestors.next().unwrap().data(), &0); /// assert!(ancestors.next().is_none()); /// ``` /// pub fn ancestors(&self, node_id: &NodeId) -> Result<Ancestors<T>, NodeIdError> { let (is_valid, error) = self.is_valid_node_id(node_id); if !is_valid { return Err(error .expect("Tree::ancestors: Missing an error value but found an invalid NodeId.")); } Ok(Ancestors::new(self, node_id.clone())) } /// /// Returns an `AncestorIds` iterator (or a `NodeIdError` if one occurred). /// /// Allows iteration over the ancestor `NodeId`s of a given `NodeId`. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); /// let node_1 = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); /// /// let mut ancestor_ids = tree.ancestor_ids(&node_1).unwrap(); /// /// assert_eq!(ancestor_ids.next().unwrap(), &root_id); /// assert!(ancestor_ids.next().is_none()); /// ``` /// pub fn ancestor_ids(&self, node_id: &NodeId) -> Result<AncestorIds<T>, NodeIdError> { let (is_valid, error) = self.is_valid_node_id(node_id); if !is_valid { return Err(error .expect("Tree::ancestor_ids: Missing an error value but found an invalid NodeId.")); } Ok(AncestorIds::new(self, node_id.clone())) } /// /// Returns a `Children` iterator (or a `NodeIdError` if one occurred). /// /// Allows iteration over the child `Node`s of a given `NodeId` directly instead of having /// to call `tree.get(...)` with a `NodeId` each time. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); /// tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); /// /// let mut children = tree.children(&root_id).unwrap(); /// /// assert_eq!(children.next().unwrap().data(), &1); /// assert!(children.next().is_none()); /// ``` /// pub fn children(&self, node_id: &NodeId) -> Result<Children<T>, NodeIdError> { let (is_valid, error) = self.is_valid_node_id(node_id); if !is_valid { return Err( error.expect("Tree::children: Missing an error value but found an invalid NodeId.") ); } Ok(Children::new(self, node_id.clone())) } /// /// Returns a `ChildrenIds` iterator (or a `NodeIdError` if one occurred). /// /// Allows iteration over the child `NodeId`s of a given `NodeId`. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); /// let node_1 = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); /// /// let mut children_ids = tree.children_ids(&root_id).unwrap(); /// /// assert_eq!(children_ids.next().unwrap(), &node_1); /// assert!(children_ids.next().is_none()); /// ``` /// pub fn children_ids(&self, node_id: &NodeId) -> Result<ChildrenIds, NodeIdError> { let (is_valid, error) = self.is_valid_node_id(node_id); if !is_valid { return Err(error .expect("Tree::children_ids: Missing an error value but found an invalid NodeId.")); } Ok(ChildrenIds::new(self, node_id.clone())) } /// Returns a `PreOrderTraversal` iterator (or a `NodeIdError` if one occurred). /// /// Allows iteration over all of the `Node`s in the sub-tree below a given `Node`. This /// iterator will always include that sub-tree "root" specified by the `NodeId` given. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); /// tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); /// /// let mut nodes = tree.traverse_pre_order(&root_id).unwrap(); /// /// assert_eq!(nodes.next().unwrap().data(), &0); /// assert_eq!(nodes.next().unwrap().data(), &1); /// assert!(nodes.next().is_none()); /// ``` /// pub fn traverse_pre_order( &self, node_id: &NodeId, ) -> Result<PreOrderTraversal<T>, NodeIdError> { let (is_valid, error) = self.is_valid_node_id(node_id); if !is_valid { return Err(error.expect( "Tree::traverse_pre_order: Missing an error value but found an invalid NodeId.", )); } Ok(PreOrderTraversal::new(self, node_id.clone())) } /// Returns a `PreOrderTraversalIds` iterator (or a `NodeIdError` if one occurred). /// /// Allows iteration over all of the `NodeId`s in the sub-tree below a given `NodeId`. This /// iterator will always include that sub-tree "root" specified by the `NodeId` given. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); /// tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); /// /// let mut nodes = tree.traverse_pre_order_ids(&root_id).unwrap(); /// /// assert_eq!(tree.get(&nodes.next().unwrap()).unwrap().data(), &0); /// assert_eq!(tree.get(&nodes.next().unwrap()).unwrap().data(), &1); /// assert!(nodes.next().is_none()); /// ``` /// pub fn traverse_pre_order_ids( &self, node_id: &NodeId, ) -> Result<PreOrderTraversalIds<T>, NodeIdError> { let (is_valid, error) = self.is_valid_node_id(&node_id); if !is_valid { return Err(error.expect( "Tree::traverse_pre_order_ids: Missing an error value but found an invalid NodeId.", )); } Ok(PreOrderTraversalIds::new(self, node_id.clone())) } /// Returns a `PostOrderTraversal` iterator (or a `NodeIdError` if one occurred). /// /// Allows iteration over all of the `Node`s in the sub-tree below a given `Node`. This /// iterator will always include that sub-tree "root" specified by the `NodeId` given. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); /// tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); /// /// let mut nodes = tree.traverse_post_order(&root_id).unwrap(); /// /// assert_eq!(nodes.next().unwrap().data(), &1); /// assert_eq!(nodes.next().unwrap().data(), &0); /// assert!(nodes.next().is_none()); /// ``` /// pub fn traverse_post_order( &self, node_id: &NodeId, ) -> Result<PostOrderTraversal<T>, NodeIdError> { let (is_valid, error) = self.is_valid_node_id(node_id); if !is_valid { return Err(error.expect( "Tree::traverse_post_order: Missing an error value but found an invalid NodeId.", )); } Ok(PostOrderTraversal::new(self, node_id.clone())) } /// Returns a `PostOrderTraversalIds` iterator (or a `NodeIdError` if one occurred). /// /// Allows iteration over all of the `NodeId`s in the sub-tree below a given `NodeId`. This /// iterator will always include that sub-tree "root" specified by the `NodeId` given. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); /// tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); /// /// let mut nodes = tree.traverse_post_order_ids(&root_id).unwrap(); /// /// assert_eq!(tree.get(&nodes.next().unwrap()).unwrap().data(), &1); /// assert_eq!(tree.get(&nodes.next().unwrap()).unwrap().data(), &0); /// assert!(nodes.next().is_none()); /// ``` /// pub fn traverse_post_order_ids( &self, node_id: &NodeId, ) -> Result<PostOrderTraversalIds, NodeIdError> { let (is_valid, error) = self.is_valid_node_id(node_id); if !is_valid { return Err(error.expect( "Tree::traverse_post_order_ids: Missing an error value but found an invalid NodeId.", )); } Ok(PostOrderTraversalIds::new(self, node_id.clone())) } /// Returns a `LevelOrderTraversal` iterator (or a `NodeIdError` if one occurred). /// /// Allows iteration over all of the `Node`s in the sub-tree below a given `Node`. This /// iterator will always include that sub-tree "root" specified by the `NodeId` given. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); /// tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); /// /// let mut nodes = tree.traverse_level_order(&root_id).unwrap(); /// /// assert_eq!(nodes.next().unwrap().data(), &0); /// assert_eq!(nodes.next().unwrap().data(), &1); /// assert!(nodes.next().is_none()); /// ``` /// pub fn traverse_level_order( &self, node_id: &NodeId, ) -> Result<LevelOrderTraversal<T>, NodeIdError> { let (is_valid, error) = self.is_valid_node_id(node_id); if !is_valid { return Err(error.expect( "Tree::traverse_level_order: Missing an error value but found an invalid NodeId.", )); } Ok(LevelOrderTraversal::new(self, node_id.clone())) } /// Returns a `LevelOrderTraversalIds` iterator (or a `NodeIdError` if one occurred). /// /// Allows iteration over all of the `NodeIds`s in the sub-tree below a given `NodeId`. This /// iterator will always include that sub-tree "root" specified by the `NodeId` given. /// /// ``` /// use id_tree::*; /// use id_tree::InsertBehavior::*; /// /// let mut tree: Tree<i32> = Tree::new(); /// let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); /// tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); /// /// let mut nodes = tree.traverse_level_order_ids(&root_id).unwrap(); /// /// assert_eq!(tree.get(&nodes.next().unwrap()).unwrap().data(), &0); /// assert_eq!(tree.get(&nodes.next().unwrap()).unwrap().data(), &1); /// assert!(nodes.next().is_none()); /// ``` /// pub fn traverse_level_order_ids( &self, node_id: &NodeId, ) -> Result<LevelOrderTraversalIds<T>, NodeIdError> { let (is_valid, error) = self.is_valid_node_id(node_id); if !is_valid { return Err(error.expect( "Tree::traverse_level_order: Missing an error value but found an invalid NodeId.", )); } Ok(LevelOrderTraversalIds::new(self, node_id.clone())) } // Nothing should make it past this function. // If there is a way for a NodeId to be invalid, it should be caught here. fn is_valid_node_id(&self, node_id: &NodeId) -> (bool, Option<NodeIdError>) { if node_id.tree_id != self.id { return (false, Some(NodeIdError::InvalidNodeIdForTree)); } if node_id.index >= self.nodes.len() { panic!( "NodeId: {:?} is out of bounds. This is most likely a bug in id_tree. Please \ report this issue!", node_id ); } unsafe { if self.nodes.get_unchecked(node_id.index).is_none() { return (false, Some(NodeIdError::NodeIdNoLongerValid)); } } (true, None) } fn find_subtree_root_between_ids<'a>( &'a self, lower_id: &'a NodeId, upper_id: &'a NodeId, ) -> Option<&'a NodeId> { if let Some(lower_parent) = self.get_unsafe(lower_id).parent() { if lower_parent == upper_id { return Some(lower_id); } else { return self.find_subtree_root_between_ids(lower_parent, upper_id); } } // lower_id has no parent, it can't be below upper_id None } fn set_as_parent_and_child(&mut self, parent_id: &NodeId, child_id: &NodeId) { self.get_mut_unsafe(parent_id).add_child(child_id.clone()); self.get_mut_unsafe(child_id) .set_parent(Some(parent_id.clone())); } fn detach_from_parent(&mut self, parent_id: &NodeId, node_id: &NodeId) { self.get_mut_unsafe(parent_id) .children_mut() .retain(|child_id| child_id != node_id); } fn insert_new_node(&mut self, new_node: Node<T>) -> NodeId { if !self.free_ids.is_empty() { let new_node_id: NodeId = self .free_ids .pop() .expect("Tree::insert_new_node: Couldn't pop from Vec with len() > 0."); self.nodes.push(Some(new_node)); self.nodes.swap_remove(new_node_id.index); new_node_id } else { let new_node_index = self.nodes.len(); self.nodes.push(Some(new_node)); self.new_node_id(new_node_index) } } fn remove_node_internal(&mut self, node_id: NodeId) -> Node<T> { if let Some(root_id) = self.root.clone() { if node_id == root_id { self.root = None; } } let mut node = self.take_node(node_id.clone()); // The only thing we care about here is dealing with "this" Node's parent's children // This Node's children's parent will be handled in different ways depending upon how this // method is called. if let Some(parent_id) = node.parent() { self.get_mut_unsafe(parent_id) .children_mut() .retain(|child_id| child_id != &node_id); } // avoid providing the caller with extra copies of NodeIds node.children_mut().clear(); node.set_parent(None); node } fn take_node(&mut self, node_id: NodeId) -> Node<T> { self.nodes.push(None); let node = self.nodes.swap_remove(node_id.index).expect( "Tree::take_node: An invalid NodeId made it past id_tree's internal checks. \ Please report this issue!", ); self.free_ids.push(node_id); node } fn new_node_id(&self, node_index: usize) -> NodeId { NodeId { tree_id: self.id, index: node_index, } } fn clear_parent(&mut self, node_id: &NodeId) { self.set_parent(node_id, None); } fn set_parent(&mut self, node_id: &NodeId, new_parent: Option<NodeId>) { self.get_mut_unsafe(node_id).set_parent(new_parent); } fn clear_parent_of_children(&mut self, node_id: &NodeId) { self.set_parent_of_children(node_id, None); } fn set_parent_of_children(&mut self, node_id: &NodeId, new_parent: Option<NodeId>) { for child_id in self.get_unsafe(node_id).children().clone() { self.set_parent(&child_id, new_parent.clone()); } } pub(crate) fn get_unsafe(&self, node_id: &NodeId) -> &Node<T> { unsafe { self.nodes.get_unchecked(node_id.index).as_ref().expect( "Tree::get_unsafe: An invalid NodeId made it past id_tree's internal \ checks. Please report this issue!", ) } } fn get_mut_unsafe(&mut self, node_id: &NodeId) -> &mut Node<T> { unsafe { self.nodes.get_unchecked_mut(node_id.index).as_mut().expect( "Tree::get_mut_unsafe: An invalid NodeId made it past id_tree's internal \ checks. Please report this issue!", ) } } } impl<T> Default for Tree<T> { fn default() -> Self { Self::new() } } impl<T> PartialEq for Tree<T> where T: PartialEq, { fn eq(&self, other: &Tree<T>) -> bool { if self.nodes.iter().filter(|x| x.is_some()).count() != other.nodes.iter().filter(|x| x.is_some()).count() { return false; } for ((i, node1), (j, node2)) in self .nodes .iter() .enumerate() .filter_map(|(i, x)| (*x).as_ref().map(|x| (i, x))) .zip( other .nodes .iter() .enumerate() .filter_map(|(i, x)| (*x).as_ref().map(|x| (i, x))), ) { let parent1_node = node1.parent.as_ref().and_then(|x| self.get(x).ok()); let parent2_node = node2.parent.as_ref().and_then(|x| other.get(x).ok()); if i != j || node1 != node2 || parent1_node != parent2_node { return false; } } true } } impl<T> Clone for Tree<T> where T: Clone, { fn clone(&self) -> Self { let tree_id = ProcessUniqueId::new(); Tree { id: tree_id, root: self.root.as_ref().map(|x| NodeId { tree_id, index: x.index, }), nodes: self .nodes .iter() .map(|x| { x.as_ref().map(|y| Node { data: y.data.clone(), parent: y.parent.as_ref().map(|z| NodeId { tree_id, index: z.index, }), children: y .children .iter() .map(|z| NodeId { tree_id, index: z.index, }) .collect(), }) }) .collect(), free_ids: self .free_ids .iter() .map(|x| NodeId { tree_id, index: x.index, }) .collect(), } } } #[cfg(test)] mod tree_builder_tests { use super::super::Node; use super::TreeBuilder; #[test] fn test_new() { let tb: TreeBuilder<i32> = TreeBuilder::new(); assert!(tb.root.is_none()); assert_eq!(tb.node_capacity, 0); assert_eq!(tb.swap_capacity, 0); } #[test] fn test_with_root() { let tb: TreeBuilder<i32> = TreeBuilder::new().with_root(Node::new(5)); assert_eq!(tb.root.unwrap().data(), &5); assert_eq!(tb.node_capacity, 0); assert_eq!(tb.swap_capacity, 0); } #[test] fn test_with_node_capacity() { let tb: TreeBuilder<i32> = TreeBuilder::new().with_node_capacity(10); assert!(tb.root.is_none()); assert_eq!(tb.node_capacity, 10); assert_eq!(tb.swap_capacity, 0); } #[test] fn test_with_swap_capacity() { let tb: TreeBuilder<i32> = TreeBuilder::new().with_swap_capacity(10); assert!(tb.root.is_none()); assert_eq!(tb.node_capacity, 0); assert_eq!(tb.swap_capacity, 10); } #[test] fn test_with_all_settings() { let tb: TreeBuilder<i32> = TreeBuilder::new() .with_root(Node::new(5)) .with_node_capacity(10) .with_swap_capacity(3); assert_eq!(tb.root.unwrap().data(), &5); assert_eq!(tb.node_capacity, 10); assert_eq!(tb.swap_capacity, 3); } #[test] fn test_build() { let tree = TreeBuilder::new() .with_root(Node::new(5)) .with_node_capacity(10) .with_swap_capacity(3) .build(); let root = tree.get(tree.root_node_id().unwrap()).unwrap(); assert_eq!(root.data(), &5); assert_eq!(tree.capacity(), 10); assert_eq!(tree.free_ids.capacity(), 3); } } #[cfg(test)] mod tree_tests { use super::super::Node; use super::super::NodeId; use super::Tree; use super::TreeBuilder; #[test] fn test_new() { let tree: Tree<i32> = Tree::new(); assert_eq!(tree.root, None); assert_eq!(tree.nodes.len(), 0); assert_eq!(tree.free_ids.len(), 0); } #[test] fn test_get() { let tree = TreeBuilder::new().with_root(Node::new(5)).build(); let root_id = tree.root.clone().unwrap(); let root = tree.get(&root_id).unwrap(); assert_eq!(root.data(), &5); } #[test] fn test_get_mut() { let mut tree = TreeBuilder::new().with_root(Node::new(5)).build(); let root_id = tree.root.clone().unwrap(); { let root = tree.get(&root_id).unwrap(); assert_eq!(root.data(), &5); } { let root = tree.get_mut(&root_id).unwrap(); *root.data_mut() = 6; } let root = tree.get(&root_id).unwrap(); assert_eq!(root.data(), &6); } #[test] fn test_set_root() { use InsertBehavior::*; let a = 5; let b = 6; let node_a = Node::new(a); let node_b = Node::new(b); let mut tree = TreeBuilder::new().build(); let node_a_id = tree.insert(node_a, AsRoot).unwrap(); let root_id = tree.root.clone().unwrap(); assert_eq!(node_a_id, root_id); { let node_a_ref = tree.get(&node_a_id).unwrap(); let root_ref = tree.get(&root_id).unwrap(); assert_eq!(node_a_ref.data(), &a); assert_eq!(root_ref.data(), &a); } let node_b_id = tree.insert(node_b, AsRoot).unwrap(); let root_id = tree.root.clone().unwrap(); assert_eq!(node_b_id, root_id); { let node_b_ref = tree.get(&node_b_id).unwrap(); let root_ref = tree.get(&root_id).unwrap(); assert_eq!(node_b_ref.data(), &b); assert_eq!(root_ref.data(), &b); let node_b_child_id = node_b_ref.children().get(0).unwrap(); let node_b_child_ref = tree.get(&node_b_child_id).unwrap(); assert_eq!(node_b_child_ref.data(), &a); } } #[test] fn test_root_node_id() { let tree = TreeBuilder::new().with_root(Node::new(5)).build(); let root_id = tree.root.clone().unwrap(); let root_node_id = tree.root_node_id().unwrap(); assert_eq!(&root_id, root_node_id); } #[test] fn test_insert_with_parent() { use InsertBehavior::*; let a = 1; let b = 2; let r = 5; let mut tree = TreeBuilder::new().with_root(Node::new(r)).build(); let node_a = Node::new(a); let node_b = Node::new(b); let root_id = tree.root.clone().unwrap(); let node_a_id = tree.insert(node_a, UnderNode(&root_id)).unwrap(); let node_b_id = tree.insert(node_b, UnderNode(&root_id)).unwrap(); let node_a_ref = tree.get(&node_a_id).unwrap(); let node_b_ref = tree.get(&node_b_id).unwrap(); assert_eq!(node_a_ref.data(), &a); assert_eq!(node_b_ref.data(), &b); assert_eq!(node_a_ref.parent().unwrap().clone(), root_id); assert_eq!(node_b_ref.parent().unwrap().clone(), root_id); let root_node_ref = tree.get(&root_id).unwrap(); let root_children: &Vec<NodeId> = root_node_ref.children(); let child_1_id = root_children.get(0).unwrap(); let child_2_id = root_children.get(1).unwrap(); let child_1_ref = tree.get(&child_1_id).unwrap(); let child_2_ref = tree.get(&child_2_id).unwrap(); assert_eq!(child_1_ref.data(), &a); assert_eq!(child_2_ref.data(), &b); } #[test] fn test_remove_node_lift_children() { use InsertBehavior::*; use RemoveBehavior::*; let mut tree = TreeBuilder::new().with_root(Node::new(5)).build(); let root_id = tree.root.clone().unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&node_1_id)).unwrap(); let node_3_id = tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); let node_1 = tree.remove_node(node_1_id.clone(), LiftChildren).unwrap(); assert_eq!(Some(&root_id), tree.root_node_id()); assert_eq!(node_1.data(), &1); assert_eq!(node_1.children().len(), 0); assert!(node_1.parent().is_none()); assert!(tree.get(&node_1_id).is_err()); let root_ref = tree.get(&root_id).unwrap(); let node_2_ref = tree.get(&node_2_id).unwrap(); let node_3_ref = tree.get(&node_3_id).unwrap(); assert_eq!(node_2_ref.data(), &2); assert_eq!(node_3_ref.data(), &3); assert_eq!(node_2_ref.parent().unwrap(), &root_id); assert_eq!(node_3_ref.parent().unwrap(), &root_id); assert!(root_ref.children().contains(&node_2_id)); assert!(root_ref.children().contains(&node_3_id)); } #[test] fn test_remove_node_orphan_children() { use InsertBehavior::*; use RemoveBehavior::*; let mut tree = TreeBuilder::new().with_root(Node::new(5)).build(); let root_id = tree.root.clone().unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&node_1_id)).unwrap(); let node_3_id = tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); let node_1 = tree.remove_node(node_1_id.clone(), OrphanChildren).unwrap(); assert_eq!(Some(&root_id), tree.root_node_id()); assert_eq!(node_1.data(), &1); assert_eq!(node_1.children().len(), 0); assert!(node_1.parent().is_none()); assert!(tree.get(&node_1_id).is_err()); let node_2_ref = tree.get(&node_2_id).unwrap(); let node_3_ref = tree.get(&node_3_id).unwrap(); assert_eq!(node_2_ref.data(), &2); assert_eq!(node_3_ref.data(), &3); assert!(node_2_ref.parent().is_none()); assert!(node_3_ref.parent().is_none()); } #[test] fn test_remove_root() { use RemoveBehavior::*; let mut tree = TreeBuilder::new().with_root(Node::new(5)).build(); let root_id = tree.root.clone().unwrap(); tree.remove_node(root_id.clone(), OrphanChildren).unwrap(); assert_eq!(None, tree.root_node_id()); let mut tree = TreeBuilder::new().with_root(Node::new(5)).build(); let root_id = tree.root.clone().unwrap(); tree.remove_node(root_id.clone(), LiftChildren).unwrap(); assert_eq!(None, tree.root_node_id()); } #[test] fn test_move_node_to_parent() { use InsertBehavior::*; use MoveBehavior::*; let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); let node_3_id = tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); // move 3 "across" the tree tree.move_node(&node_3_id, ToParent(&node_2_id)).unwrap(); assert!(tree.get(&root_id).unwrap().children().contains(&node_1_id)); assert!(tree.get(&root_id).unwrap().children().contains(&node_2_id)); assert!(tree .get(&node_2_id,) .unwrap() .children() .contains(&node_3_id,)); // move 3 "up" the tree tree.move_node(&node_3_id, ToParent(&root_id)).unwrap(); assert!(tree.get(&root_id).unwrap().children().contains(&node_1_id)); assert!(tree.get(&root_id).unwrap().children().contains(&node_2_id)); assert!(tree.get(&root_id).unwrap().children().contains(&node_3_id)); // move 3 "down" (really this is across though) the tree tree.move_node(&node_3_id, ToParent(&node_1_id)).unwrap(); assert!(tree.get(&root_id).unwrap().children().contains(&node_1_id)); assert!(tree.get(&root_id).unwrap().children().contains(&node_2_id)); assert!(tree .get(&node_1_id,) .unwrap() .children() .contains(&node_3_id,)); // move 1 "down" the tree tree.move_node(&node_1_id, ToParent(&node_3_id)).unwrap(); assert!(tree.get(&root_id).unwrap().children().contains(&node_2_id)); assert!(tree.get(&root_id).unwrap().children().contains(&node_3_id)); assert!(tree .get(&node_3_id,) .unwrap() .children() .contains(&node_1_id,)); // note: node_1 is at the lowest point in the tree before these insertions. let node_4_id = tree.insert(Node::new(4), UnderNode(&node_1_id)).unwrap(); let node_5_id = tree.insert(Node::new(5), UnderNode(&node_4_id)).unwrap(); // move 3 "down" the tree tree.move_node(&node_3_id, ToParent(&node_5_id)).unwrap(); assert!(tree.get(&root_id).unwrap().children().contains(&node_2_id)); assert!(tree.get(&root_id).unwrap().children().contains(&node_1_id)); assert!(tree .get(&node_1_id,) .unwrap() .children() .contains(&node_4_id,)); assert!(tree .get(&node_4_id,) .unwrap() .children() .contains(&node_5_id,)); assert!(tree .get(&node_5_id,) .unwrap() .children() .contains(&node_3_id,)); // move root "down" the tree tree.move_node(&root_id, ToParent(&node_2_id)).unwrap(); assert!(tree.get(&node_2_id).unwrap().children().contains(&root_id)); assert!(tree.get(&root_id).unwrap().children().contains(&node_1_id)); assert!(tree .get(&node_1_id,) .unwrap() .children() .contains(&node_4_id,)); assert!(tree .get(&node_4_id,) .unwrap() .children() .contains(&node_5_id,)); assert!(tree .get(&node_5_id,) .unwrap() .children() .contains(&node_3_id,)); assert_eq!(tree.root_node_id(), Some(&node_2_id)); } #[test] fn test_move_node_to_root() { use InsertBehavior::*; // test move with existing root { let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&node_1_id)).unwrap(); tree.move_node_to_root(&node_2_id).unwrap(); assert_eq!(tree.root_node_id(), Some(&node_2_id)); assert!(tree.get(&node_2_id).unwrap().children().contains(&root_id)); assert!(!tree .get(&node_1_id,) .unwrap() .children() .contains(&node_2_id,)); } // test move with existing root and with orphan { let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&node_1_id)).unwrap(); tree.remove_node_orphan_children(node_1_id).unwrap(); tree.move_node_to_root(&node_2_id).unwrap(); assert_eq!(tree.root_node_id(), Some(&node_2_id)); assert!(tree.get(&node_2_id).unwrap().children().contains(&root_id)); assert_eq!(tree.get(&root_id).unwrap().children().len(), 0); } // test move without root and with orphan { let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&node_1_id)).unwrap(); tree.remove_node_orphan_children(root_id).unwrap(); tree.move_node_to_root(&node_1_id).unwrap(); assert_eq!(tree.root_node_id(), Some(&node_1_id)); assert!(tree .get(&node_1_id,) .unwrap() .children() .contains(&node_2_id,)); assert_eq!(tree.get(&node_1_id).unwrap().children().len(), 1); } } #[test] fn test_find_subtree_root_below_upper_id() { use InsertBehavior::*; let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&node_1_id)).unwrap(); let node_3_id = tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); let node_4_id = tree.insert(Node::new(4), UnderNode(&node_2_id)).unwrap(); let sub_root = tree.find_subtree_root_between_ids(&node_1_id, &root_id); assert_eq!(sub_root, Some(&node_1_id)); let sub_root = tree.find_subtree_root_between_ids(&root_id, &node_1_id); //invert for None assert_eq!(sub_root, None); let sub_root = tree.find_subtree_root_between_ids(&node_2_id, &root_id); assert_eq!(sub_root, Some(&node_1_id)); let sub_root = tree.find_subtree_root_between_ids(&root_id, &node_2_id); //invert for None assert_eq!(sub_root, None); let sub_root = tree.find_subtree_root_between_ids(&node_3_id, &node_1_id); assert_eq!(sub_root, Some(&node_3_id)); let sub_root = tree.find_subtree_root_between_ids(&node_1_id, &node_3_id); //invert for None assert_eq!(sub_root, None); let sub_root = tree.find_subtree_root_between_ids(&node_4_id, &root_id); assert_eq!(sub_root, Some(&node_1_id)); let sub_root = tree.find_subtree_root_between_ids(&root_id, &node_4_id); //invert for None assert_eq!(sub_root, None); } #[test] fn test_swap_nodes_take_children() { use InsertBehavior::*; use SwapBehavior::*; // test across swap { let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); let node_3_id = tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); let node_4_id = tree.insert(Node::new(4), UnderNode(&node_2_id)).unwrap(); tree.swap_nodes(&node_3_id, &node_4_id, TakeChildren) .unwrap(); assert!(tree .get(&node_1_id,) .unwrap() .children() .contains(&node_4_id,)); assert!(tree .get(&node_2_id,) .unwrap() .children() .contains(&node_3_id,)); } // test ordering via swap { let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); tree.swap_nodes(&node_1_id, &node_2_id, TakeChildren) .unwrap(); let children = tree.get(&root_id).unwrap().children(); assert!(children[0] == node_2_id); assert!(children[1] == node_1_id); } // test swap down { let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); let node_3_id = tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); tree.swap_nodes(&root_id, &node_3_id, TakeChildren).unwrap(); assert_eq!(tree.root_node_id(), Some(&node_3_id)); assert!(tree.get(&node_3_id).unwrap().children().contains(&root_id)); let children = tree.get(&root_id).unwrap().children(); assert!(children[0] == node_1_id); assert!(children[1] == node_2_id); } // test swap down without root { let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); let node_3_id = tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); tree.swap_nodes(&node_1_id, &node_3_id, TakeChildren) .unwrap(); assert!(tree .get(&node_3_id,) .unwrap() .children() .contains(&node_1_id,)); let children = tree.get(&root_id).unwrap().children(); assert!(children[0] == node_3_id); assert!(children[1] == node_2_id); } } #[test] fn test_swap_nodes_leave_children() { use InsertBehavior::*; use MoveBehavior::*; use RemoveBehavior::*; use SwapBehavior::*; // test across swap // from: // 0 // / \ // 1 2 // | | // 3 4 // to: // 0 // / \ // 2 1 // | | // 3 4 { let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); let node_3_id = tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); let node_4_id = tree.insert(Node::new(4), UnderNode(&node_2_id)).unwrap(); tree.swap_nodes(&node_1_id, &node_2_id, LeaveChildren) .unwrap(); let root_children = tree.get(&root_id).unwrap().children(); assert_eq!(root_children[0], node_2_id); assert_eq!(root_children[1], node_1_id); assert_eq!(tree.get(&node_3_id).unwrap().parent(), Some(&node_2_id)); assert_eq!(tree.get(&node_4_id).unwrap().parent(), Some(&node_1_id)); assert!(tree .get(&node_1_id,) .unwrap() .children() .contains(&node_4_id,)); assert!(tree .get(&node_2_id,) .unwrap() .children() .contains(&node_3_id,)); } // test down swap (with no space between nodes) // from: // 0 // / \ // 1 2 // | | // 3 4 // to: // 0 // / \ // 3 2 // | | // 1 4 { let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); let node_3_id = tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); tree.insert(Node::new(4), UnderNode(&node_2_id)).unwrap(); tree.swap_nodes(&node_1_id, &node_3_id, LeaveChildren) .unwrap(); let root_children = tree.get(&root_id).unwrap().children(); assert_eq!(root_children[0], node_3_id); assert_eq!(root_children[1], node_2_id); assert_eq!(tree.get(&node_3_id).unwrap().parent(), Some(&root_id)); assert_eq!(tree.get(&node_1_id).unwrap().parent(), Some(&node_3_id)); assert!(tree .get(&node_3_id,) .unwrap() .children() .contains(&node_1_id,)); assert_eq!(tree.get(&node_1_id).unwrap().children().len(), 0); } // test down swap (with space between nodes) // from: // 0 // / \ // 1 2 // | | // 3 4 // | // 5 // to: // 0 // / \ // 5 2 // | | // 3 4 // | // 1 { let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); let node_3_id = tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); tree.insert(Node::new(4), UnderNode(&node_2_id)).unwrap(); let node_5_id = tree.insert(Node::new(5), UnderNode(&node_3_id)).unwrap(); tree.swap_nodes(&node_1_id, &node_5_id, LeaveChildren) .unwrap(); let root_children = tree.get(&root_id).unwrap().children(); assert_eq!(root_children[0], node_5_id); assert_eq!(root_children[1], node_2_id); assert_eq!(tree.get(&node_3_id).unwrap().parent(), Some(&node_5_id)); assert_eq!(tree.get(&node_1_id).unwrap().parent(), Some(&node_3_id)); assert_eq!(tree.get(&node_5_id).unwrap().parent(), Some(&root_id)); assert!(tree .get(&node_3_id,) .unwrap() .children() .contains(&node_1_id,)); assert!(tree .get(&node_5_id,) .unwrap() .children() .contains(&node_3_id,)); assert_eq!(tree.get(&node_1_id).unwrap().children().len(), 0); } // test down swap (with root) // from: // 0 // / \ // 1 2 // | | // 3 4 // to: // 4 // / \ // 1 2 // | | // 3 0 { let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); let node_4_id = tree.insert(Node::new(4), UnderNode(&node_2_id)).unwrap(); tree.swap_nodes(&root_id, &node_4_id, LeaveChildren) .unwrap(); assert_eq!(tree.root_node_id(), Some(&node_4_id)); let node_4_children = tree.get(&node_4_id).unwrap().children(); assert_eq!(node_4_children[0], node_1_id); assert_eq!(node_4_children[1], node_2_id); assert_eq!(tree.get(&node_1_id).unwrap().parent(), Some(&node_4_id)); assert_eq!(tree.get(&node_2_id).unwrap().parent(), Some(&node_4_id)); assert_eq!(tree.get(&root_id).unwrap().parent(), Some(&node_2_id)); assert!(tree.get(&node_2_id).unwrap().children().contains(&root_id)); assert_eq!(tree.get(&root_id).unwrap().children().len(), 0); } // test orphaned swap (no root) // from: // 1 2 // | | // 3 4 // to: // 2 1 // | | // 3 4 { let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); let node_3_id = tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); let node_4_id = tree.insert(Node::new(4), UnderNode(&node_2_id)).unwrap(); tree.remove_node(root_id, OrphanChildren).unwrap(); tree.swap_nodes(&node_1_id, &node_2_id, LeaveChildren) .unwrap(); assert_eq!(tree.root_node_id(), None); assert_eq!(tree.get(&node_3_id).unwrap().parent(), Some(&node_2_id)); assert_eq!(tree.get(&node_4_id).unwrap().parent(), Some(&node_1_id)); assert!(tree .get(&node_2_id,) .unwrap() .children() .contains(&node_3_id,)); assert!(tree .get(&node_1_id,) .unwrap() .children() .contains(&node_4_id,)); } // test orphaned swap (1 is root) // from: // 1 2 // | | // 3 4 // to: // 2 1 // | | // 3 4 { let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); let node_3_id = tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); let node_4_id = tree.insert(Node::new(4), UnderNode(&node_2_id)).unwrap(); tree.remove_node(root_id, OrphanChildren).unwrap(); tree.move_node(&node_1_id, ToRoot).unwrap(); tree.swap_nodes(&node_1_id, &node_2_id, LeaveChildren) .unwrap(); assert_eq!(tree.root_node_id(), Some(&node_2_id)); assert_eq!(tree.get(&node_3_id).unwrap().parent(), Some(&node_2_id)); assert_eq!(tree.get(&node_4_id).unwrap().parent(), Some(&node_1_id)); assert!(tree .get(&node_2_id,) .unwrap() .children() .contains(&node_3_id,)); assert!(tree .get(&node_1_id,) .unwrap() .children() .contains(&node_4_id,)); } } #[test] fn test_swap_nodes_children_only() { use InsertBehavior::*; use SwapBehavior::*; // test across swap // swap(1,2) // from: // 0 // / \ // 1 2 // / \ \ // 3 4 5 // to: // 0 // / \ // 1 2 // / / \ // 5 3 4 { let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); let node_3_id = tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); let node_4_id = tree.insert(Node::new(4), UnderNode(&node_1_id)).unwrap(); let node_5_id = tree.insert(Node::new(5), UnderNode(&node_2_id)).unwrap(); tree.swap_nodes(&node_1_id, &node_2_id, ChildrenOnly) .unwrap(); let root_children = tree.get(&root_id).unwrap().children(); assert_eq!(root_children[0], node_1_id); assert_eq!(root_children[1], node_2_id); assert_eq!(tree.get(&node_3_id).unwrap().parent(), Some(&node_2_id)); assert_eq!(tree.get(&node_4_id).unwrap().parent(), Some(&node_2_id)); assert_eq!(tree.get(&node_5_id).unwrap().parent(), Some(&node_1_id)); assert!(tree .get(&node_1_id,) .unwrap() .children() .contains(&node_5_id,)); assert!(tree .get(&node_2_id,) .unwrap() .children() .contains(&node_3_id,)); assert!(tree .get(&node_2_id,) .unwrap() .children() .contains(&node_4_id,)); } // test down swap (with no space between nodes) // swap(1,3) // from: // 0 // / \ // 1 2 // / \ \ // 3 4 5 // | | // 6 7 // to: // 0 // / \ // 1 2 // / \ \ // 6 3 5 // | // 4 // | // 7 { let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); let node_3_id = tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); let node_4_id = tree.insert(Node::new(4), UnderNode(&node_1_id)).unwrap(); tree.insert(Node::new(5), UnderNode(&node_2_id)).unwrap(); let node_6_id = tree.insert(Node::new(6), UnderNode(&node_3_id)).unwrap(); tree.insert(Node::new(7), UnderNode(&node_4_id)).unwrap(); tree.swap_nodes(&node_1_id, &node_3_id, ChildrenOnly) .unwrap(); let root_children = tree.get(&root_id).unwrap().children(); assert_eq!(root_children[0], node_1_id); assert_eq!(root_children[1], node_2_id); assert_eq!(tree.get(&node_3_id).unwrap().parent(), Some(&node_1_id)); assert_eq!(tree.get(&node_1_id).unwrap().parent(), Some(&root_id)); assert_eq!(tree.get(&node_4_id).unwrap().parent(), Some(&node_3_id)); assert_eq!(tree.get(&node_6_id).unwrap().parent(), Some(&node_1_id)); let node_1_children = tree.get(&node_1_id).unwrap().children(); assert_eq!(node_1_children[0], node_6_id); assert_eq!(node_1_children[1], node_3_id); assert!(tree .get(&node_3_id,) .unwrap() .children() .contains(&node_4_id,)); } // test down swap (with space between nodes) // swap(1, 6) // from: // 0 // / \ // 1 2 // / \ \ // 3 4 5 // | | // 6 7 // to: // 0 // / \ // 1 2 // / \ // 6 5 // / \ // 3 4 // | // 7 { let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); let node_3_id = tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); let node_4_id = tree.insert(Node::new(4), UnderNode(&node_1_id)).unwrap(); tree.insert(Node::new(5), UnderNode(&node_2_id)).unwrap(); let node_6_id = tree.insert(Node::new(6), UnderNode(&node_3_id)).unwrap(); tree.insert(Node::new(7), UnderNode(&node_4_id)).unwrap(); tree.swap_nodes(&node_1_id, &node_6_id, ChildrenOnly) .unwrap(); let root_children = tree.get(&root_id).unwrap().children(); assert_eq!(root_children[0], node_1_id); assert_eq!(root_children[1], node_2_id); assert_eq!(tree.get(&node_3_id).unwrap().parent(), Some(&node_6_id)); assert_eq!(tree.get(&node_4_id).unwrap().parent(), Some(&node_6_id)); assert_eq!(tree.get(&node_6_id).unwrap().parent(), Some(&node_1_id)); assert!(tree .get(&node_1_id,) .unwrap() .children() .contains(&node_6_id,)); assert!(!tree .get(&node_1_id,) .unwrap() .children() .contains(&node_3_id,)); assert!(!tree .get(&node_1_id,) .unwrap() .children() .contains(&node_4_id,)); assert!(tree .get(&node_6_id,) .unwrap() .children() .contains(&node_3_id,)); assert!(tree .get(&node_6_id,) .unwrap() .children() .contains(&node_4_id,)); } // test down swap (with root) // swap(0,1) // from: // 0 // / \ // 1 2 // / \ \ // 3 4 5 // | | // 6 7 // to: // 0 // /|\ // 3 4 1 // | | | // 6 7 2 // | // 5 { let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); let node_3_id = tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); let node_4_id = tree.insert(Node::new(4), UnderNode(&node_1_id)).unwrap(); tree.insert(Node::new(5), UnderNode(&node_2_id)).unwrap(); tree.insert(Node::new(6), UnderNode(&node_3_id)).unwrap(); tree.insert(Node::new(7), UnderNode(&node_4_id)).unwrap(); tree.swap_nodes(&root_id, &node_1_id, ChildrenOnly).unwrap(); let root_children = tree.get(&root_id).unwrap().children(); assert_eq!(root_children[0], node_3_id); assert_eq!(root_children[1], node_4_id); assert_eq!(root_children[2], node_1_id); assert_eq!(tree.get(&node_1_id).unwrap().parent(), Some(&root_id)); assert_eq!(tree.get(&node_3_id).unwrap().parent(), Some(&root_id)); assert_eq!(tree.get(&node_4_id).unwrap().parent(), Some(&root_id)); assert_eq!(tree.get(&node_2_id).unwrap().parent(), Some(&node_1_id)); let node_1_children = tree.get(&node_1_id).unwrap().children(); assert_eq!(node_1_children[0], node_2_id); } } #[test] fn test_tree_height() { use InsertBehavior::*; use RemoveBehavior::*; // empty tree let mut tree = Tree::new(); assert_eq!(0, tree.height()); // the tree with single root node let root_id = tree.insert(Node::new(1), AsRoot).unwrap(); assert_eq!(1, tree.height()); // root node with single child let child_1_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); assert_eq!(2, tree.height()); // root node with two children let child_2_id = tree.insert(Node::new(3), UnderNode(&root_id)).unwrap(); assert_eq!(2, tree.height()); // grandson tree.insert(Node::new(4), UnderNode(&child_1_id)).unwrap(); assert_eq!(3, tree.height()); // remove child_1 and gradson tree.remove_node(child_1_id, DropChildren).unwrap(); assert_eq!(2, tree.height()); // remove child_2 tree.remove_node(child_2_id, LiftChildren).unwrap(); assert_eq!(1, tree.height()); } #[test] fn test_partial_eq() { use InsertBehavior::*; let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); // ensure PartialEq doesn't work when the number of used nodes are not equal { let mut other = Tree::new(); let root_id = other.insert(Node::new(0), AsRoot).unwrap(); other.insert(Node::new(1), UnderNode(&root_id)).unwrap(); other.insert(Node::new(2), UnderNode(&root_id)).unwrap(); assert_ne!(tree, other); } // ensure PartialEq doesn't work when the data is not equal { let mut other = Tree::new(); let root_id = other.insert(Node::new(0), AsRoot).unwrap(); let id = other.insert(Node::new(1), UnderNode(&root_id)).unwrap(); other.insert(Node::new(2), UnderNode(&root_id)).unwrap(); other.insert(Node::new(4), UnderNode(&id)).unwrap(); assert_ne!(tree, other); } // ensure PartialEq doesn't work when the parents aren't equal { let mut other = Tree::new(); let root_id = other.insert(Node::new(0), AsRoot).unwrap(); other.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let id = other.insert(Node::new(2), UnderNode(&root_id)).unwrap(); other.insert(Node::new(3), UnderNode(&id)).unwrap(); assert_ne!(tree, other); } // ensure PartialEq works even if the number of free spots in Tree.nodes is different { let mut other = Tree::new(); let root_id = other.insert(Node::new(0), AsRoot).unwrap(); let id = other.insert(Node::new(1), UnderNode(&root_id)).unwrap(); other.insert(Node::new(2), UnderNode(&root_id)).unwrap(); other.insert(Node::new(3), UnderNode(&id)).unwrap(); let to_delete = other.insert(Node::new(42), UnderNode(&root_id)).unwrap(); other.take_node(to_delete); assert_ne!( tree.nodes.iter().filter(|x| x.is_none()).count(), other.nodes.iter().filter(|x| x.is_none()).count() ); assert_eq!(tree, other); } // ensure PartialEq doesn't work when the Node's index are different { let mut other = Tree::new(); let root_id = other.insert(Node::new(0), AsRoot).unwrap(); let to_delete = other.insert(Node::new(42), UnderNode(&root_id)).unwrap(); let id = other.insert(Node::new(1), UnderNode(&root_id)).unwrap(); other.insert(Node::new(2), UnderNode(&root_id)).unwrap(); other.insert(Node::new(3), UnderNode(&id)).unwrap(); other.take_node(to_delete); assert_ne!(tree, other); } } #[test] fn test_clone() { use InsertBehavior::*; let mut tree = Tree::new(); let root_id = tree.insert(Node::new(0), AsRoot).unwrap(); let node_1_id = tree.insert(Node::new(1), UnderNode(&root_id)).unwrap(); let node_2_id = tree.insert(Node::new(2), UnderNode(&root_id)).unwrap(); let _node_3_id = tree.insert(Node::new(3), UnderNode(&node_1_id)).unwrap(); let node_4_id = tree.insert(Node::new(4), UnderNode(&node_2_id)).unwrap(); tree.take_node(node_4_id); let cloned = tree.clone(); assert!(cloned.root.is_some()); let tree_id = cloned.id; // ensure cloned tree has a new id assert_ne!(tree.id, tree_id); // ensure cloned tree's root is using the new tree id assert_eq!(cloned.root.as_ref().map(|x| x.tree_id), Some(tree_id)); // ensure cloned tree's free_ids is using the new tree id assert_eq!(cloned.free_ids[0].tree_id, tree_id); // ensure nodes' parent are using the new tree id assert_eq!( cloned.nodes[1] .as_ref() .map(|x| x.parent.as_ref().map(|x| x.tree_id)), Some(Some(tree_id)) ); // ensure nodes' children are using the new tree id assert_eq!( cloned .children(cloned.root.as_ref().unwrap()) .unwrap() .next() .map(|x| x.parent.as_ref().map(|x| x.tree_id)), Some(Some(tree_id)) ); // ensure the tree and the cloned tree are equal assert_eq!(tree, cloned); } }
#[doc = "Reader of register AHB1ENR"] pub type R = crate::R<u32, super::AHB1ENR>; #[doc = "Writer for register AHB1ENR"] pub type W = crate::W<u32, super::AHB1ENR>; #[doc = "Register AHB1ENR `reset()`'s with value 0x0100"] impl crate::ResetValue for super::AHB1ENR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x0100 } } #[doc = "Reader of field `DMA1EN`"] pub type DMA1EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DMA1EN`"] pub struct DMA1EN_W<'a> { w: &'a mut W, } impl<'a> DMA1EN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `DMA2EN`"] pub type DMA2EN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DMA2EN`"] pub struct DMA2EN_W<'a> { w: &'a mut W, } impl<'a> DMA2EN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `DMAMUXEN`"] pub type DMAMUXEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DMAMUXEN`"] pub struct DMAMUXEN_W<'a> { w: &'a mut W, } impl<'a> DMAMUXEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `CORDICEN`"] pub type CORDICEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CORDICEN`"] pub struct CORDICEN_W<'a> { w: &'a mut W, } impl<'a> CORDICEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `FMACEN`"] pub type FMACEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FMACEN`"] pub struct FMACEN_W<'a> { w: &'a mut W, } impl<'a> FMACEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `FLASHEN`"] pub type FLASHEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FLASHEN`"] pub struct FLASHEN_W<'a> { w: &'a mut W, } impl<'a> FLASHEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `CRCEN`"] pub type CRCEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CRCEN`"] pub struct CRCEN_W<'a> { w: &'a mut W, } impl<'a> CRCEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } impl R { #[doc = "Bit 0 - DMA1 clock enable"] #[inline(always)] pub fn dma1en(&self) -> DMA1EN_R { DMA1EN_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - DMA2 clock enable"] #[inline(always)] pub fn dma2en(&self) -> DMA2EN_R { DMA2EN_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - DMAMUX clock enable"] #[inline(always)] pub fn dmamuxen(&self) -> DMAMUXEN_R { DMAMUXEN_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - CORDIC clock enable"] #[inline(always)] pub fn cordicen(&self) -> CORDICEN_R { CORDICEN_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - FMAC clock enable"] #[inline(always)] pub fn fmacen(&self) -> FMACEN_R { FMACEN_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 8 - Flash memory interface clock enable"] #[inline(always)] pub fn flashen(&self) -> FLASHEN_R { FLASHEN_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 12 - CRC clock enable"] #[inline(always)] pub fn crcen(&self) -> CRCEN_R { CRCEN_R::new(((self.bits >> 12) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - DMA1 clock enable"] #[inline(always)] pub fn dma1en(&mut self) -> DMA1EN_W { DMA1EN_W { w: self } } #[doc = "Bit 1 - DMA2 clock enable"] #[inline(always)] pub fn dma2en(&mut self) -> DMA2EN_W { DMA2EN_W { w: self } } #[doc = "Bit 2 - DMAMUX clock enable"] #[inline(always)] pub fn dmamuxen(&mut self) -> DMAMUXEN_W { DMAMUXEN_W { w: self } } #[doc = "Bit 3 - CORDIC clock enable"] #[inline(always)] pub fn cordicen(&mut self) -> CORDICEN_W { CORDICEN_W { w: self } } #[doc = "Bit 4 - FMAC clock enable"] #[inline(always)] pub fn fmacen(&mut self) -> FMACEN_W { FMACEN_W { w: self } } #[doc = "Bit 8 - Flash memory interface clock enable"] #[inline(always)] pub fn flashen(&mut self) -> FLASHEN_W { FLASHEN_W { w: self } } #[doc = "Bit 12 - CRC clock enable"] #[inline(always)] pub fn crcen(&mut self) -> CRCEN_W { CRCEN_W { w: self } } }
use serde::Serialize; use tide::{Body, Request}; #[derive(Debug, Serialize)] struct Item { name: String, value: i32, } #[async_std::main] async fn main() -> tide::Result<()> { let mut app = tide::new(); app.at("/items").get(find_items); app.listen("127.0.0.1:8080").await?; Ok(()) } async fn find_items(_: Request<()>) -> tide::Result { let res = vec![ Item { name: "item-1".into(), value: 1 }, Item { name: "item-2".into(), value: 2 }, Item { name: "item-3".into(), value: 3 }, ]; Body::from_json(&res) .map(Body::into) }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; use common_catalog::plan::PartStatistics; use common_catalog::plan::Partitions; use common_catalog::plan::PartitionsShuffleKind; use common_catalog::plan::PushDownInfo; use common_catalog::table::Table; use common_catalog::table_context::TableContext; use common_exception::Result; use common_expression::types::number::UInt8Type; use common_expression::types::NumberDataType; use common_expression::utils::FromData; use common_expression::DataBlock; use common_expression::TableDataType; use common_expression::TableField; use common_expression::TableSchemaRefExt; use common_meta_app::schema::TableIdent; use common_meta_app::schema::TableInfo; use common_meta_app::schema::TableMeta; use crate::table::SystemTablePart; use crate::SyncOneBlockSystemTable; use crate::SyncSystemTable; pub struct OneTable { table_info: TableInfo, } impl SyncSystemTable for OneTable { const NAME: &'static str = "system.one"; fn get_table_info(&self) -> &TableInfo { &self.table_info } fn get_full_data(&self, _ctx: Arc<dyn TableContext>) -> Result<DataBlock> { Ok(DataBlock::new_from_columns(vec![UInt8Type::from_data( vec![1u8], )])) } fn get_partitions( &self, _ctx: Arc<dyn TableContext>, _push_downs: Option<PushDownInfo>, ) -> Result<(PartStatistics, Partitions)> { Ok(( PartStatistics::new_exact(1, 1, 1, 1), Partitions::create_nolazy(PartitionsShuffleKind::Seq, vec![Arc::new(Box::new( SystemTablePart, ))]), )) } } impl OneTable { pub fn create(table_id: u64) -> Arc<dyn Table> { let schema = TableSchemaRefExt::create(vec![TableField::new( "dummy", TableDataType::Number(NumberDataType::UInt8), )]); let table_info = TableInfo { desc: "'system'.'one'".to_string(), name: "one".to_string(), ident: TableIdent::new(table_id, 0), meta: TableMeta { schema, engine: "SystemOne".to_string(), ..Default::default() }, ..Default::default() }; SyncOneBlockSystemTable::create(OneTable { table_info }) } }
#![feature(plugin)] #![plugin(rocket_codegen)] #![feature(plugin, custom_derive, const_fn)] #![plugin(rocket_codegen)] extern crate rocket; #[macro_use] extern crate diesel; extern crate dotenv; extern crate r2d2; extern crate r2d2_diesel; pub mod schema; use diesel::pg::PgConnection; use r2d2::{ Pool, Config }; use r2d2_diesel::ConnectionManager; use dotenv::dotenv; use std::env; use rocket::Rocket; // can be moved to routes.rs #[get("/")] fn index() -> &'static str { "Hello, world!" } fn rocket() -> Rocket { dotenv().ok(); // Url to the database as set in the DATABASE_URL environment variable. let database_url = env::var("DATABASE_URL") .expect("DATABASE_URL must be set"); // Initializes database pool with r2d2. let config = Config::default(); let manager = ConnectionManager::<PgConnection>::new(database_url); let pool = Pool::new(config, manager).expect("Failed to create pool."); rocket::ignite() .manage(pool) .mount("/", routes![index]) } fn main() { rocket().launch(); }
// auto generated, do not modify. // created: Wed Jan 20 00:44:03 2016 // src-file: /QtQml/qqmlcomponent.h // dst-file: /src/qml/qqmlcomponent.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use super::super::core::qobject::QObject; // 771 use std::ops::Deref; use super::qqmlcontext::QQmlContext; // 773 use super::qqmlengine::QQmlEngine; // 773 use super::super::core::qurl::QUrl; // 771 use super::super::core::qstring::QString; // 771 use super::super::core::qbytearray::QByteArray; // 771 use super::qqmlincubator::QQmlIncubator; // 773 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QQmlComponent_Class_Size() -> c_int; // proto: void QQmlComponent::~QQmlComponent(); fn _ZN13QQmlComponentD2Ev(qthis: u64 /* *mut c_void*/); // proto: QQmlContext * QQmlComponent::creationContext(); fn _ZNK13QQmlComponent15creationContextEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QObject * QQmlComponent::create(QQmlContext * context); fn _ZN13QQmlComponent6createEP11QQmlContext(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QQmlComponent::QQmlComponent(QQmlEngine * , QObject * parent); fn _ZN13QQmlComponentC2EP10QQmlEngineP7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void); // proto: bool QQmlComponent::isReady(); fn _ZNK13QQmlComponent7isReadyEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QQmlComponent::QQmlComponent(QObject * parent); fn _ZN13QQmlComponentC2EP7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: qreal QQmlComponent::progress(); fn _ZNK13QQmlComponent8progressEv(qthis: u64 /* *mut c_void*/) -> c_double; // proto: QUrl QQmlComponent::url(); fn _ZNK13QQmlComponent3urlEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: static QQmlComponentAttached * QQmlComponent::qmlAttachedProperties(QObject * ); fn _ZN13QQmlComponent21qmlAttachedPropertiesEP7QObject(arg0: *mut c_void); // proto: bool QQmlComponent::isError(); fn _ZNK13QQmlComponent7isErrorEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QQmlComponent::completeCreate(); fn _ZN13QQmlComponent14completeCreateEv(qthis: u64 /* *mut c_void*/); // proto: bool QQmlComponent::isLoading(); fn _ZNK13QQmlComponent9isLoadingEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: void QQmlComponent::loadUrl(const QUrl & url); fn _ZN13QQmlComponent7loadUrlERK4QUrl(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: void QQmlComponent::QQmlComponent(QQmlEngine * , const QUrl & url, QObject * parent); fn _ZN13QQmlComponentC2EP10QQmlEngineRK4QUrlP7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void); // proto: QObject * QQmlComponent::beginCreate(QQmlContext * ); fn _ZN13QQmlComponent11beginCreateEP11QQmlContext(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void; // proto: void QQmlComponent::setData(const QByteArray & , const QUrl & baseUrl); fn _ZN13QQmlComponent7setDataERK10QByteArrayRK4QUrl(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void); // proto: QString QQmlComponent::errorString(); fn _ZNK13QQmlComponent11errorStringEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: QList<QQmlError> QQmlComponent::errors(); fn _ZNK13QQmlComponent6errorsEv(qthis: u64 /* *mut c_void*/); // proto: void QQmlComponent::QQmlComponent(const QQmlComponent & ); fn _ZN13QQmlComponentC2ERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: const QMetaObject * QQmlComponent::metaObject(); fn _ZNK13QQmlComponent10metaObjectEv(qthis: u64 /* *mut c_void*/); // proto: void QQmlComponent::create(QQmlIncubator & , QQmlContext * context, QQmlContext * forContext); fn _ZN13QQmlComponent6createER13QQmlIncubatorP11QQmlContextS3_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void); // proto: void QQmlComponent::QQmlComponent(QQmlEngine * , const QString & fileName, QObject * parent); fn _ZN13QQmlComponentC2EP10QQmlEngineRK7QStringP7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void); // proto: bool QQmlComponent::isNull(); fn _ZNK13QQmlComponent6isNullEv(qthis: u64 /* *mut c_void*/) -> c_char; fn QQmlComponent_SlotProxy_connect__ZN13QQmlComponent15progressChangedEd(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void); } // <= ext block end // body block begin => // class sizeof(QQmlComponent)=1 #[derive(Default)] pub struct QQmlComponent { qbase: QObject, pub qclsinst: u64 /* *mut c_void*/, pub _progressChanged: QQmlComponent_progressChanged_signal, pub _statusChanged: QQmlComponent_statusChanged_signal, } impl /*struct*/ QQmlComponent { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QQmlComponent { return QQmlComponent{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; } } impl Deref for QQmlComponent { type Target = QObject; fn deref(&self) -> &QObject { return & self.qbase; } } impl AsRef<QObject> for QQmlComponent { fn as_ref(& self) -> & QObject { return & self.qbase; } } // proto: void QQmlComponent::~QQmlComponent(); impl /*struct*/ QQmlComponent { pub fn free<RetType, T: QQmlComponent_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QQmlComponent_free<RetType> { fn free(self , rsthis: & QQmlComponent) -> RetType; } // proto: void QQmlComponent::~QQmlComponent(); impl<'a> /*trait*/ QQmlComponent_free<()> for () { fn free(self , rsthis: & QQmlComponent) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QQmlComponentD2Ev()}; unsafe {_ZN13QQmlComponentD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: QQmlContext * QQmlComponent::creationContext(); impl /*struct*/ QQmlComponent { pub fn creationContext<RetType, T: QQmlComponent_creationContext<RetType>>(& self, overload_args: T) -> RetType { return overload_args.creationContext(self); // return 1; } } pub trait QQmlComponent_creationContext<RetType> { fn creationContext(self , rsthis: & QQmlComponent) -> RetType; } // proto: QQmlContext * QQmlComponent::creationContext(); impl<'a> /*trait*/ QQmlComponent_creationContext<QQmlContext> for () { fn creationContext(self , rsthis: & QQmlComponent) -> QQmlContext { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QQmlComponent15creationContextEv()}; let mut ret = unsafe {_ZNK13QQmlComponent15creationContextEv(rsthis.qclsinst)}; let mut ret1 = QQmlContext::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QObject * QQmlComponent::create(QQmlContext * context); impl /*struct*/ QQmlComponent { pub fn create<RetType, T: QQmlComponent_create<RetType>>(& self, overload_args: T) -> RetType { return overload_args.create(self); // return 1; } } pub trait QQmlComponent_create<RetType> { fn create(self , rsthis: & QQmlComponent) -> RetType; } // proto: QObject * QQmlComponent::create(QQmlContext * context); impl<'a> /*trait*/ QQmlComponent_create<QObject> for (&'a QQmlContext) { fn create(self , rsthis: & QQmlComponent) -> QObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QQmlComponent6createEP11QQmlContext()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {_ZN13QQmlComponent6createEP11QQmlContext(rsthis.qclsinst, arg0)}; let mut ret1 = QObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QQmlComponent::QQmlComponent(QQmlEngine * , QObject * parent); impl /*struct*/ QQmlComponent { pub fn new<T: QQmlComponent_new>(value: T) -> QQmlComponent { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QQmlComponent_new { fn new(self) -> QQmlComponent; } // proto: void QQmlComponent::QQmlComponent(QQmlEngine * , QObject * parent); impl<'a> /*trait*/ QQmlComponent_new for (&'a QQmlEngine, &'a QObject) { fn new(self) -> QQmlComponent { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QQmlComponentC2EP10QQmlEngineP7QObject()}; let ctysz: c_int = unsafe{QQmlComponent_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; unsafe {_ZN13QQmlComponentC2EP10QQmlEngineP7QObject(qthis_ph, arg0, arg1)}; let qthis: u64 = qthis_ph; let rsthis = QQmlComponent{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: bool QQmlComponent::isReady(); impl /*struct*/ QQmlComponent { pub fn isReady<RetType, T: QQmlComponent_isReady<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isReady(self); // return 1; } } pub trait QQmlComponent_isReady<RetType> { fn isReady(self , rsthis: & QQmlComponent) -> RetType; } // proto: bool QQmlComponent::isReady(); impl<'a> /*trait*/ QQmlComponent_isReady<i8> for () { fn isReady(self , rsthis: & QQmlComponent) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QQmlComponent7isReadyEv()}; let mut ret = unsafe {_ZNK13QQmlComponent7isReadyEv(rsthis.qclsinst)}; return ret as i8; // return 1; } } // proto: void QQmlComponent::QQmlComponent(QObject * parent); impl<'a> /*trait*/ QQmlComponent_new for (&'a QObject) { fn new(self) -> QQmlComponent { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QQmlComponentC2EP7QObject()}; let ctysz: c_int = unsafe{QQmlComponent_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; unsafe {_ZN13QQmlComponentC2EP7QObject(qthis_ph, arg0)}; let qthis: u64 = qthis_ph; let rsthis = QQmlComponent{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: qreal QQmlComponent::progress(); impl /*struct*/ QQmlComponent { pub fn progress<RetType, T: QQmlComponent_progress<RetType>>(& self, overload_args: T) -> RetType { return overload_args.progress(self); // return 1; } } pub trait QQmlComponent_progress<RetType> { fn progress(self , rsthis: & QQmlComponent) -> RetType; } // proto: qreal QQmlComponent::progress(); impl<'a> /*trait*/ QQmlComponent_progress<f64> for () { fn progress(self , rsthis: & QQmlComponent) -> f64 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QQmlComponent8progressEv()}; let mut ret = unsafe {_ZNK13QQmlComponent8progressEv(rsthis.qclsinst)}; return ret as f64; // return 1; } } // proto: QUrl QQmlComponent::url(); impl /*struct*/ QQmlComponent { pub fn url<RetType, T: QQmlComponent_url<RetType>>(& self, overload_args: T) -> RetType { return overload_args.url(self); // return 1; } } pub trait QQmlComponent_url<RetType> { fn url(self , rsthis: & QQmlComponent) -> RetType; } // proto: QUrl QQmlComponent::url(); impl<'a> /*trait*/ QQmlComponent_url<QUrl> for () { fn url(self , rsthis: & QQmlComponent) -> QUrl { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QQmlComponent3urlEv()}; let mut ret = unsafe {_ZNK13QQmlComponent3urlEv(rsthis.qclsinst)}; let mut ret1 = QUrl::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: static QQmlComponentAttached * QQmlComponent::qmlAttachedProperties(QObject * ); impl /*struct*/ QQmlComponent { pub fn qmlAttachedProperties_s<RetType, T: QQmlComponent_qmlAttachedProperties_s<RetType>>( overload_args: T) -> RetType { return overload_args.qmlAttachedProperties_s(); // return 1; } } pub trait QQmlComponent_qmlAttachedProperties_s<RetType> { fn qmlAttachedProperties_s(self ) -> RetType; } // proto: static QQmlComponentAttached * QQmlComponent::qmlAttachedProperties(QObject * ); impl<'a> /*trait*/ QQmlComponent_qmlAttachedProperties_s<()> for (&'a QObject) { fn qmlAttachedProperties_s(self ) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QQmlComponent21qmlAttachedPropertiesEP7QObject()}; let arg0 = self.qclsinst as *mut c_void; unsafe {_ZN13QQmlComponent21qmlAttachedPropertiesEP7QObject(arg0)}; // return 1; } } // proto: bool QQmlComponent::isError(); impl /*struct*/ QQmlComponent { pub fn isError<RetType, T: QQmlComponent_isError<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isError(self); // return 1; } } pub trait QQmlComponent_isError<RetType> { fn isError(self , rsthis: & QQmlComponent) -> RetType; } // proto: bool QQmlComponent::isError(); impl<'a> /*trait*/ QQmlComponent_isError<i8> for () { fn isError(self , rsthis: & QQmlComponent) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QQmlComponent7isErrorEv()}; let mut ret = unsafe {_ZNK13QQmlComponent7isErrorEv(rsthis.qclsinst)}; return ret as i8; // return 1; } } // proto: void QQmlComponent::completeCreate(); impl /*struct*/ QQmlComponent { pub fn completeCreate<RetType, T: QQmlComponent_completeCreate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.completeCreate(self); // return 1; } } pub trait QQmlComponent_completeCreate<RetType> { fn completeCreate(self , rsthis: & QQmlComponent) -> RetType; } // proto: void QQmlComponent::completeCreate(); impl<'a> /*trait*/ QQmlComponent_completeCreate<()> for () { fn completeCreate(self , rsthis: & QQmlComponent) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QQmlComponent14completeCreateEv()}; unsafe {_ZN13QQmlComponent14completeCreateEv(rsthis.qclsinst)}; // return 1; } } // proto: bool QQmlComponent::isLoading(); impl /*struct*/ QQmlComponent { pub fn isLoading<RetType, T: QQmlComponent_isLoading<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isLoading(self); // return 1; } } pub trait QQmlComponent_isLoading<RetType> { fn isLoading(self , rsthis: & QQmlComponent) -> RetType; } // proto: bool QQmlComponent::isLoading(); impl<'a> /*trait*/ QQmlComponent_isLoading<i8> for () { fn isLoading(self , rsthis: & QQmlComponent) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QQmlComponent9isLoadingEv()}; let mut ret = unsafe {_ZNK13QQmlComponent9isLoadingEv(rsthis.qclsinst)}; return ret as i8; // return 1; } } // proto: void QQmlComponent::loadUrl(const QUrl & url); impl /*struct*/ QQmlComponent { pub fn loadUrl<RetType, T: QQmlComponent_loadUrl<RetType>>(& self, overload_args: T) -> RetType { return overload_args.loadUrl(self); // return 1; } } pub trait QQmlComponent_loadUrl<RetType> { fn loadUrl(self , rsthis: & QQmlComponent) -> RetType; } // proto: void QQmlComponent::loadUrl(const QUrl & url); impl<'a> /*trait*/ QQmlComponent_loadUrl<()> for (&'a QUrl) { fn loadUrl(self , rsthis: & QQmlComponent) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QQmlComponent7loadUrlERK4QUrl()}; let arg0 = self.qclsinst as *mut c_void; unsafe {_ZN13QQmlComponent7loadUrlERK4QUrl(rsthis.qclsinst, arg0)}; // return 1; } } // proto: void QQmlComponent::QQmlComponent(QQmlEngine * , const QUrl & url, QObject * parent); impl<'a> /*trait*/ QQmlComponent_new for (&'a QQmlEngine, &'a QUrl, &'a QObject) { fn new(self) -> QQmlComponent { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QQmlComponentC2EP10QQmlEngineRK4QUrlP7QObject()}; let ctysz: c_int = unsafe{QQmlComponent_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.qclsinst as *mut c_void; unsafe {_ZN13QQmlComponentC2EP10QQmlEngineRK4QUrlP7QObject(qthis_ph, arg0, arg1, arg2)}; let qthis: u64 = qthis_ph; let rsthis = QQmlComponent{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QObject * QQmlComponent::beginCreate(QQmlContext * ); impl /*struct*/ QQmlComponent { pub fn beginCreate<RetType, T: QQmlComponent_beginCreate<RetType>>(& self, overload_args: T) -> RetType { return overload_args.beginCreate(self); // return 1; } } pub trait QQmlComponent_beginCreate<RetType> { fn beginCreate(self , rsthis: & QQmlComponent) -> RetType; } // proto: QObject * QQmlComponent::beginCreate(QQmlContext * ); impl<'a> /*trait*/ QQmlComponent_beginCreate<QObject> for (&'a QQmlContext) { fn beginCreate(self , rsthis: & QQmlComponent) -> QObject { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QQmlComponent11beginCreateEP11QQmlContext()}; let arg0 = self.qclsinst as *mut c_void; let mut ret = unsafe {_ZN13QQmlComponent11beginCreateEP11QQmlContext(rsthis.qclsinst, arg0)}; let mut ret1 = QObject::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QQmlComponent::setData(const QByteArray & , const QUrl & baseUrl); impl /*struct*/ QQmlComponent { pub fn setData<RetType, T: QQmlComponent_setData<RetType>>(& self, overload_args: T) -> RetType { return overload_args.setData(self); // return 1; } } pub trait QQmlComponent_setData<RetType> { fn setData(self , rsthis: & QQmlComponent) -> RetType; } // proto: void QQmlComponent::setData(const QByteArray & , const QUrl & baseUrl); impl<'a> /*trait*/ QQmlComponent_setData<()> for (&'a QByteArray, &'a QUrl) { fn setData(self , rsthis: & QQmlComponent) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QQmlComponent7setDataERK10QByteArrayRK4QUrl()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; unsafe {_ZN13QQmlComponent7setDataERK10QByteArrayRK4QUrl(rsthis.qclsinst, arg0, arg1)}; // return 1; } } // proto: QString QQmlComponent::errorString(); impl /*struct*/ QQmlComponent { pub fn errorString<RetType, T: QQmlComponent_errorString<RetType>>(& self, overload_args: T) -> RetType { return overload_args.errorString(self); // return 1; } } pub trait QQmlComponent_errorString<RetType> { fn errorString(self , rsthis: & QQmlComponent) -> RetType; } // proto: QString QQmlComponent::errorString(); impl<'a> /*trait*/ QQmlComponent_errorString<QString> for () { fn errorString(self , rsthis: & QQmlComponent) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QQmlComponent11errorStringEv()}; let mut ret = unsafe {_ZNK13QQmlComponent11errorStringEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: QList<QQmlError> QQmlComponent::errors(); impl /*struct*/ QQmlComponent { pub fn errors<RetType, T: QQmlComponent_errors<RetType>>(& self, overload_args: T) -> RetType { return overload_args.errors(self); // return 1; } } pub trait QQmlComponent_errors<RetType> { fn errors(self , rsthis: & QQmlComponent) -> RetType; } // proto: QList<QQmlError> QQmlComponent::errors(); impl<'a> /*trait*/ QQmlComponent_errors<()> for () { fn errors(self , rsthis: & QQmlComponent) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QQmlComponent6errorsEv()}; unsafe {_ZNK13QQmlComponent6errorsEv(rsthis.qclsinst)}; // return 1; } } // proto: void QQmlComponent::QQmlComponent(const QQmlComponent & ); impl<'a> /*trait*/ QQmlComponent_new for (&'a QQmlComponent) { fn new(self) -> QQmlComponent { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QQmlComponentC2ERKS_()}; let ctysz: c_int = unsafe{QQmlComponent_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; unsafe {_ZN13QQmlComponentC2ERKS_(qthis_ph, arg0)}; let qthis: u64 = qthis_ph; let rsthis = QQmlComponent{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: const QMetaObject * QQmlComponent::metaObject(); impl /*struct*/ QQmlComponent { pub fn metaObject<RetType, T: QQmlComponent_metaObject<RetType>>(& self, overload_args: T) -> RetType { return overload_args.metaObject(self); // return 1; } } pub trait QQmlComponent_metaObject<RetType> { fn metaObject(self , rsthis: & QQmlComponent) -> RetType; } // proto: const QMetaObject * QQmlComponent::metaObject(); impl<'a> /*trait*/ QQmlComponent_metaObject<()> for () { fn metaObject(self , rsthis: & QQmlComponent) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QQmlComponent10metaObjectEv()}; unsafe {_ZNK13QQmlComponent10metaObjectEv(rsthis.qclsinst)}; // return 1; } } // proto: void QQmlComponent::create(QQmlIncubator & , QQmlContext * context, QQmlContext * forContext); impl<'a> /*trait*/ QQmlComponent_create<()> for (&'a QQmlIncubator, &'a QQmlContext, &'a QQmlContext) { fn create(self , rsthis: & QQmlComponent) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QQmlComponent6createER13QQmlIncubatorP11QQmlContextS3_()}; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.qclsinst as *mut c_void; unsafe {_ZN13QQmlComponent6createER13QQmlIncubatorP11QQmlContextS3_(rsthis.qclsinst, arg0, arg1, arg2)}; // return 1; } } // proto: void QQmlComponent::QQmlComponent(QQmlEngine * , const QString & fileName, QObject * parent); impl<'a> /*trait*/ QQmlComponent_new for (&'a QQmlEngine, &'a QString, &'a QObject) { fn new(self) -> QQmlComponent { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN13QQmlComponentC2EP10QQmlEngineRK7QStringP7QObject()}; let ctysz: c_int = unsafe{QQmlComponent_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.0.qclsinst as *mut c_void; let arg1 = self.1.qclsinst as *mut c_void; let arg2 = self.2.qclsinst as *mut c_void; unsafe {_ZN13QQmlComponentC2EP10QQmlEngineRK7QStringP7QObject(qthis_ph, arg0, arg1, arg2)}; let qthis: u64 = qthis_ph; let rsthis = QQmlComponent{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: bool QQmlComponent::isNull(); impl /*struct*/ QQmlComponent { pub fn isNull<RetType, T: QQmlComponent_isNull<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isNull(self); // return 1; } } pub trait QQmlComponent_isNull<RetType> { fn isNull(self , rsthis: & QQmlComponent) -> RetType; } // proto: bool QQmlComponent::isNull(); impl<'a> /*trait*/ QQmlComponent_isNull<i8> for () { fn isNull(self , rsthis: & QQmlComponent) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK13QQmlComponent6isNullEv()}; let mut ret = unsafe {_ZNK13QQmlComponent6isNullEv(rsthis.qclsinst)}; return ret as i8; // return 1; } } #[derive(Default)] // for QQmlComponent_progressChanged pub struct QQmlComponent_progressChanged_signal{poi:u64} impl /* struct */ QQmlComponent { pub fn progressChanged(&self) -> QQmlComponent_progressChanged_signal { return QQmlComponent_progressChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QQmlComponent_progressChanged_signal { pub fn connect<T: QQmlComponent_progressChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QQmlComponent_progressChanged_signal_connect { fn connect(self, sigthis: QQmlComponent_progressChanged_signal); } #[derive(Default)] // for QQmlComponent_statusChanged pub struct QQmlComponent_statusChanged_signal{poi:u64} impl /* struct */ QQmlComponent { pub fn statusChanged(&self) -> QQmlComponent_statusChanged_signal { return QQmlComponent_statusChanged_signal{poi:self.qclsinst}; } } impl /* struct */ QQmlComponent_statusChanged_signal { pub fn connect<T: QQmlComponent_statusChanged_signal_connect>(self, overload_args: T) { overload_args.connect(self); } } pub trait QQmlComponent_statusChanged_signal_connect { fn connect(self, sigthis: QQmlComponent_statusChanged_signal); } // progressChanged(qreal) extern fn QQmlComponent_progressChanged_signal_connect_cb_0(rsfptr:fn(f64), arg0: c_double) { println!("{}:{}", file!(), line!()); let rsarg0 = arg0 as f64; rsfptr(rsarg0); } extern fn QQmlComponent_progressChanged_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn(f64)>, arg0: c_double) { println!("{}:{}", file!(), line!()); let rsfptr = unsafe{Box::from_raw(rsfptr_raw)}; let rsarg0 = arg0 as f64; // rsfptr(rsarg0); unsafe{(*rsfptr_raw)(rsarg0)}; } impl /* trait */ QQmlComponent_progressChanged_signal_connect for fn(f64) { fn connect(self, sigthis: QQmlComponent_progressChanged_signal) { // do smth... // self as u64; // error for Fn, Ok for fn self as *mut c_void as u64; self as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QQmlComponent_progressChanged_signal_connect_cb_0 as *mut c_void; let arg2 = self as *mut c_void; unsafe {QQmlComponent_SlotProxy_connect__ZN13QQmlComponent15progressChangedEd(arg0, arg1, arg2)}; } } impl /* trait */ QQmlComponent_progressChanged_signal_connect for Box<Fn(f64)> { fn connect(self, sigthis: QQmlComponent_progressChanged_signal) { // do smth... // Box::into_raw(self) as u64; // Box::into_raw(self) as *mut c_void; let arg0 = sigthis.poi as *mut c_void; let arg1 = QQmlComponent_progressChanged_signal_connect_cb_box_0 as *mut c_void; let arg2 = Box::into_raw(Box::new(self)) as *mut c_void; unsafe {QQmlComponent_SlotProxy_connect__ZN13QQmlComponent15progressChangedEd(arg0, arg1, arg2)}; } } // <= body block end
use crate::db::Message; use hyper::{ Body, Request, Response, }; use routerify::{ Middleware, Router, RouterBuilder, ext::RequestExt, RequestInfo }; use anyhow::{Error, Result}; use tracing::{info, error}; use tokio::sync::mpsc::Sender; mod api; async fn logger(req: Request<Body>) -> Result<Request<Body>> { info!("{} {} {}", req.remote_addr(), req.method(), req.uri().path()); Ok(req) } async fn home_handler(_: Request<Body>) -> Result<Response<Body>> { Ok(Response::new(Body::from("Url Mapper in Rust!"))) } async fn error_handler(err: routerify::RouteError, _: RequestInfo) -> Response<Body> { error!("{}", err); let status = match err.to_string().as_str() { "Unauthorized Access" => hyper::StatusCode::UNAUTHORIZED, _ => hyper::StatusCode::INTERNAL_SERVER_ERROR, }; Response::builder() .status(status) .body(Body::from(format!("Something went wrong: {}", err))) .unwrap() } macro_rules! sender_failed { ($m: expr, $f: tt) => { match $m { Ok(_) => {}, Err(e) => { error!("Database Manager failed to get {}! error: {}", $f, e); return Ok(Response::builder() .status(hyper::StatusCode::INTERNAL_SERVER_ERROR) .body(Body::from(format!("Something went wrong: {}", e))) .unwrap()); } } } } macro_rules! recv_failed { ($m: expr) => { match $m { Ok(d) => d, Err(e) => { error!("Database Manager returned error: {}", e); return Ok(Response::builder() .status(hyper::StatusCode::NOT_FOUND) .body(Body::from("Key does not exist")) .unwrap()); } } } } async fn redirect_handler(req: Request<Body>) -> Result<Response<Body>> { let sender = req.data::<Sender<Message>>().unwrap(); let key = req.param("key").unwrap(); let (tx, rx) = tokio::sync::oneshot::channel(); sender_failed!( sender .send(Message::GetUrlMap { key: key.clone(), resp: tx}) .await, "GetUrlMap"); let url_map = recv_failed!(rx.await.unwrap()); Ok(Response::builder() .header(hyper::header::LOCATION, url_map.url.clone()) .status(hyper::StatusCode::SEE_OTHER) .body(Body::from(format!("redirecting to url: {}", url_map.url))) .unwrap()) } pub fn router() -> RouterBuilder<Body, Error> { Router::builder() .middleware(Middleware::pre(logger)) .get("/", home_handler) .get("/:key", redirect_handler) .scope("/api", api::router()) .err_handler_with_info(error_handler) }
//! Prints counter manipulation methods. use crate::ir; use crate::print; use proc_macro2::TokenStream; use quote::quote; /// Prints the value of a counter increment. If `use_old` is true, only takes into account /// decisions that have been propagated. pub fn increment_amount( value: &ir::CounterVal, use_old: bool, ctx: &print::Context, ) -> print::Value { match value { ir::CounterVal::Code(code) => print::Value::new_const(code, ctx), ir::CounterVal::Choice(choice) => print::Value::from_store(choice, use_old, ctx), } } /// Returns `+=` or `*=` depending on if the counter is additive or multiplicative. fn increment_operator(kind: ir::CounterKind) -> TokenStream { match kind { ir::CounterKind::Add => quote!(+=), ir::CounterKind::Mul => quote!(*=), } } /// Returns the operator performing the inverse operation of `op`. fn inverse_operator(op: ir::CounterKind) -> TokenStream { match op { ir::CounterKind::Add => quote!(-), ir::CounterKind::Mul => quote!(/), } } impl quote::ToTokens for ir::CounterKind { fn to_tokens(&self, stream: &mut TokenStream) { match *self { ir::CounterKind::Add => quote!(+).to_tokens(stream), ir::CounterKind::Mul => quote!(*).to_tokens(stream), } } } /// Prints code to rescrict the increment amount if necessary. `delayed` indicates if the /// actions should be taken immediately, or pushed into an action list. // TODO(cleanup): print the full method instead of just part of its body. // TODO(cleanup): simplify the template pub fn restrict_incr_amount( incr_amount: &ir::ChoiceInstance, current_incr_amount: &print::Value, op: ir::CounterKind, delayed: bool, ctx: &print::Context, ) -> TokenStream { let max_val = print::ValueIdent::new("max_val", ir::ValueType::Constant); let neg_op = inverse_operator(op); let restricted_value_type = incr_amount.value_type(ctx.ir_desc).full_type(); let restricted_value = print::value::integer_domain_constructor( ir::CmpOp::Leq, &max_val.into(), restricted_value_type, ctx, ); let restricted_value_name = restricted_value.create_ident("value"); let apply_restriction = print::choice::restrict(incr_amount, &restricted_value_name.into(), delayed, ctx); let min_incr_amount = current_incr_amount.get_min(ctx); quote! { else if incr_status.is_true() { let max_val = new_values.max #neg_op current.min #op #min_incr_amount; let value = #restricted_value; #apply_restriction } } } /// Prints a method that computes the value of a counter, only taking propagated actions /// into account. // TODO(cleanup): print the full method instead of just part of its body. // TODO(cleanup): simplify the template pub fn compute_counter_body( value: &ir::CounterVal, incr: &ir::ChoiceInstance, incr_condition: &ir::ValueSet, op: ir::CounterKind, visibility: ir::CounterVisibility, ctx: &print::Context, ) -> TokenStream { let value_getter = increment_amount(value, true, ctx); let value: print::Value = value_getter.create_ident("value").into(); let value_min = value.get_min(ctx); let value_max = value.get_max(ctx); let incr_getter = print::Value::from_store(incr, true, ctx); let incr_condition = print::value_set::print(incr_condition, ctx); let op_eq = increment_operator(op); let update_max = if visibility == ir::CounterVisibility::NoMax { None } else { Some(quote! { if (#incr_condition).intersects(incr) { counter_val.max #op_eq #value_max; } }) }; quote! { let value = #value_getter; let incr = #incr_getter; #update_max if (#incr_condition).contains(incr) { counter_val.min #op_eq #value_min; } } }
pub mod oauth1;
use crate::AST; use std::collections::HashMap; #[derive(Debug, Clone)] pub struct Env { vars: HashMap<EnvKey, AST>, natives: HashMap<String, fn(Vec<AST>) -> Result<AST, String>>, frames: u8, debug: bool, } #[derive(Debug, Clone, Hash, PartialEq, Eq)] struct EnvKey { frame: u8, name: String, } impl EnvKey { pub fn new(frame: u8, name: String) -> EnvKey { EnvKey { frame: frame, name: name, } } } impl Env { pub fn new(debug: bool) -> Env { return Env { vars: HashMap::new(), natives: HashMap::new(), frames: 1, debug: debug, }; } pub fn debug(&self) -> bool { self.debug } pub fn frame_push(&mut self) -> () { self.frames += 1; if self.debug { println!("{}> FRAME PUSH", self.frames); } } pub fn frame_pop(&mut self) -> () { if self.debug { println!("{}< FRAME POP", self.frames); } self.frames -= 1; } pub fn add_var(&mut self, name: String, value: AST) -> () { let key = EnvKey::new(self.frames, name); if self.debug { println!("{}: SET {:?} <- {:?}", self.frames, key, value); } self.vars.insert(key, value); } pub fn get_var(&self, name: String) -> Option<&AST> { let mut i: u8 = self.frames; while i > 0 { let key = EnvKey::new(i, name.clone()); let var = self.vars.get(&key); if var.is_some() { if self.debug { println!("{}: GET {:?}", self.frames, key); } return var; } i -= 1; } return None; } pub fn del_var(&mut self, name: String) -> () { let key = EnvKey::new(self.frames, name); if self.debug { println!("{}: DEL {:?}", self.frames, key); } self.vars.remove(&key); } pub fn add_native(&mut self, name: String, value: fn(Vec<AST>) -> Result<AST, String>) -> () { self.natives.insert(name, value); } pub fn get_native(&mut self, name: String) -> Option<&fn(Vec<AST>) -> Result<AST, String>> { self.natives.get(&name) } }
pub struct Stride<I> { iter: I, stride: usize, } impl<I> Iterator for Stride<I> where I: Iterator { type Item = I::Item; #[inline] fn next(&mut self) -> Option<I::Item> { let ret = self.iter.next(); if self.stride > 1 { self.iter.nth(self.stride - 2); } ret } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { if self.stride > 0 { match self.iter.size_hint() { (lower, None) => (lower / self.stride, None), (lower, Some(upper)) => (lower / self.stride, Some(upper / self.stride)) } } else { self.iter.size_hint() } } } pub struct MapPairs<B, I, F> where I: Iterator, F: Fn([I::Item; 2]) -> B { iter: I, f: F, } impl<B, I, F> Iterator for MapPairs<B, I, F> where I: Iterator , F: Fn([I::Item; 2]) -> B { type Item = B; #[inline] fn next(&mut self) -> Option<B> { let a = self.iter.next(); let b = self.iter.next(); match (a,b) { (Some(x), Some(y)) => Some((self.f)([x,y])), _ => None } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } pub struct Scan1<B, I, F> where F: FnMut(&mut I::Item, I::Item) -> Option<B>, I: Iterator { iter: I, f: F, state: Option<I::Item>, } impl<B, I, F> Iterator for Scan1<B, I, F> where F: FnMut(&mut I::Item, I::Item) -> Option<B>, I: Iterator { type Item = B; #[inline] fn next(&mut self) -> Option<B> { // If the current state is None, then grab the first element if self.state.is_none() { self.state = self.iter.next(); } match self.state { None => None, Some(_) => self.iter.next().and_then(|a| (self.f)(self.state.as_mut().unwrap(), a)) } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let (_, upper) = self.iter.size_hint(); (0, upper) // can't know a lower bound, due to the scan function } } pub trait IteratorExtra: Iterator + Sized { /// This will traverse the iterator `stride` elements at a time. /// /// The first element in the input iterator will be returned, then `stride - 1` /// elements will be skipped. A stride of 0 is the same as a stride of 1 is the /// same as an unaltered iterator. /// /// # Example /// /// ```rust /// use IteratorExtras::IteratorExtra; /// let xs = vec![0u, 1, 2, 3, 4, 5]; /// let strided: Vec<usize> = xs.into_iter().stride(3).collect(); /// assert_eq!(strided, vec![0u, 3]); /// ``` /// fn stride(self, stride: usize) -> Stride<Self> { Stride { iter: self, stride: stride } } /// This will take chunks of 2 elements in the iterator, and map a closure of two elements /// to each chunk. /// /// If there are an odd number of elements, the last element will be ignored. /// /// # Example /// /// ```rust /// use IteratorExtras::IteratorExtra; /// let xs = vec![0i, 1, 5, 8, 10]; /// let pairwise_diffs: Vec<int> = xs.into_iter().map_pairs(|[l,r]| r - l).collect(); /// assert_eq!(pairwise_diffs, vec![1i, 3]); /// ``` fn map_pairs<B, F>(self, f: F) -> MapPairs<B, Self, F> where F: Fn([Self::Item; 2]) -> B { MapPairs { iter: self, f: f } } /// This is just like `scan`, but using the first element as the initial state variable /// /// # Example /// /// ```rust /// use IteratorExtras::IteratorExtra; /// let xs = vec![0i, 1, 3, 6, 10]; /// let diffs: Vec<int> = xs.into_iter().scan1(|st, x| { /// let diff = x - *st; /// *st = x; /// Some(diff) /// }).collect(); /// assert_eq!(diffs, vec![1i, 2, 3, 4]); /// ``` fn scan1<B, F>(self, f: F) -> Scan1<B, Self, F> where F: FnMut(&mut Self::Item, Self::Item) -> Option<B> { Scan1 { iter: self, f: f, state: None } } } impl<I> IteratorExtra for I where I: Iterator { }
use std::env::args; use std::path::Path; use std::fmt::Display; use std::io::Error; use walkdir::WalkDir; use histo::Histogram; fn process_entry(histogram: &mut Histogram, entry: &walkdir::DirEntry) -> Result<(), Error> { if entry.file_type().is_file() { let mut count = 0; for fe in fiemap::fiemap(entry.path())? { fe?; count += 1; } histogram.add(count as u64); } Ok(()) } fn process<P: AsRef<Path> + Display>(dir: P) { let mut histogram = Histogram::with_buckets(10); for entry in WalkDir::new(dir.as_ref()) .same_file_system(true) { let entry = match entry { Ok(entry) => entry, Err(e) => { eprintln!("{}: Error {:?}", dir, e); continue; }, }; if let Err(e) = process_entry(&mut histogram, &entry) { eprintln!("{}: Error {:?}", entry.path().display(), e); } } println!("{}:\n{}\n", dir, histogram); } fn main() { for f in args().skip(1) { process(f); } }
/// detekuje číslo na obrázku, viz zadání /// před kompilací je potřeba nainstalovat tesseract tak, /// aby libleptonica a libtesseract byly v PATH /// a nainstalovat ces language pack pro tesseract /// /// ### Kompilace: /// ```bash /// cargo build --release /// ``` /// Binární soubor bude target/release/odmociny /// /// ### Spouštení přes Cargo /// ```bash /// cargo run --release /// ``` /// /// moje prostředí: Arch Linux x86_64, GCC, Rust 1.34.0-nightly (c1d2d83ca 2019-03-01) extern crate tesseract; extern crate promptly; extern crate yansi; use yansi::Paint; use promptly::prompt; use std::fs::read_dir; use std::process::exit; fn main() { let cesta: String = prompt(format!("{}", Paint::yellow("Zadejte cestu ke složce"))); eprintln!("{}", Paint::yellow("Vyhodnocuji..")); // projde složku a všechno prožene tesseractem match read_dir(&cesta) { Err(e) => { eprintln!("Nepodařilo se přečíst složku: {}", e); exit(-1) }, // filtrování Ok(r) => for soubor in r.filter(|e| e.is_ok()) .map(|e| e.unwrap()) .map(|f| f.path()) .filter(|f| !f.is_dir()) .map(|f| f.to_str() .unwrap() .to_string()) .filter(|s| s.to_lowercase().contains("png")) { let mut t = tesseract::Tesseract::new(); t.set_lang("ces"); t.set_image(&soubor); t.recognize(); match t.get_text() { a @ "1" | a @ "2" | a @ "3" | a @ "4" | a @ "5" | a @ "6" | a @ "7" | a @ "8" | a @ "9" | a @ "0"z => println!("{} - {}", soubor, a), _ => println!("{} - X", soubor) } } } }
pub use VkDebugReportObjectTypeEXT::*; #[repr(u32)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum VkDebugReportObjectTypeEXT { VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT = 0, VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT = 1, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT = 2, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT = 3, VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT = 4, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT = 5, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT = 6, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT = 7, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT = 8, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT = 9, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT = 10, VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT = 11, VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT = 12, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_VIEW_EXT = 13, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT = 14, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT = 15, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_CACHE_EXT = 16, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT = 17, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT = 18, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT = 19, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT = 20, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_EXT = 21, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT = 22, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT = 23, VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT = 24, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_POOL_EXT = 25, VK_DEBUG_REPORT_OBJECT_TYPE_SURFACE_KHR_EXT = 26, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT = 27, VK_DEBUG_REPORT_OBJECT_TYPE_DEBUG_REPORT_EXT = 28, VK_DEBUG_REPORT_OBJECT_TYPE_DISPLAY_KHR_EXT = 29, VK_DEBUG_REPORT_OBJECT_TYPE_DISPLAY_MODE_KHR_EXT = 30, VK_DEBUG_REPORT_OBJECT_TYPE_OBJECT_TABLE_NVX_EXT = 31, VK_DEBUG_REPORT_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX_EXT = 32, VK_DEBUG_REPORT_OBJECT_TYPE_VALIDATION_CACHE_EXT_EXT = 33, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_EXT = 1000156000, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_EXT = 1000085000, VK_DEBUG_REPORT_OBJECT_TYPE_ACCELERATION_STRUCTURE_NV_EXT = 1000165000, }
// xfail-boot // error-pattern: cyclic import import zed.bar; import bar.zed; fn main(vec[str] args) { log "loop"; }
pub mod exam_service; pub mod student_answer_service; pub mod student_exam_service;
use std::fmt::Debug; use crate::util::AsAny; use self::conversion::{AsEvent, AsNetworkEvent}; use self::util::CloneableEvent; pub trait Event: AsAny + AsEvent + AsNetworkEvent + Debug + Send { } #[typetag::serde(tag = "event")] pub trait NetworkEvent: CloneableEvent + Event { } impl<T: 'static + NetworkEvent> Event for T { } pub mod component; pub mod core; pub mod layer; pub mod network; pub mod scene; pub mod conversion; mod util;
use rlb::backend::{Backend, BackendError, BackendPool}; use rlb::balancing::RoundRobinBalancing; use std::sync::atomic::Ordering; #[test] fn backend_new_test() { let backend = Backend::new(String::from(":5000"), Some(String::from("/health"))); assert_eq!(backend.alive.load(Ordering::Acquire), false); assert_eq!(backend.byte_traffic(), 0); assert_eq!(backend.health_endpoint(), &Some("/health".to_string())); } #[test] fn backend_pool_len() { let mut pool = BackendPool::new(Box::new(RoundRobinBalancing::new())); assert_eq!(pool.len(), 0); pool.push(Backend::new(String::from(":5000"), None)); assert_eq!(pool.len(), 1); } #[test] fn backend_pool_from_list() { let pool = BackendPool::from_backends_list( vec![ Backend::new(String::from(":5000"), None), Backend::new(String::from(":5001"), None), ], Box::new(RoundRobinBalancing::new()), ); assert_eq!(pool.len(), 2); } #[test] fn backend_pool_next_backend_round_robin() { let mut pool = BackendPool::from_backends_list( vec![ Backend::new(String::from(":5000"), None), Backend::new(String::from(":5001"), None), ], Box::new(RoundRobinBalancing::new()), ); let index = pool.next_backend(); assert_eq!(index, Err(BackendError::NoBackendAlive)); pool[1].alive.store(true, Ordering::Relaxed); let index = pool.next_backend(); assert_eq!(index, Ok(1)); }
#[cfg(target_arch = "aarch64")] fn main() { // TODO: compile the ffi file in here"; println!("cargo:rustc-link-search=native=armffi/lib"); println!("cargo:rustc-link-lib=static=armffi"); } #[cfg(target_arch = "x86_64")] fn main() { }